﻿// ----------------------GLOBAL VARIABLES -----------------------------------
    var gmap = null;
    var dynMapOv = null;    
    var mapext = null;
    var idtask = null;
    var qtask = null;
    var gsvc = null;
    var squery = null;
    var ovs = [];
    var marker = null;
    var mapExtension = null;
    var query = null;
    var gOverlays = [];
    var gmarkers = [];
    var neighborhoodschoolnumber = null;
    var infocontent = "<div style='height:130px; width:310px'>";
                infocontent += "<b>{School}</b><br/>";
                infocontent += "{Street}<br/>";
                infocontent += "{City}, {State}&nbsp;&nbsp;{ZipCode}<br />";
                infocontent += "{Phone}<br />";
                infocontent += "Principal: {Principal}<br />";
                infocontent += "<a href='{website}'>School Website</a><br />";
                infocontent += "Montessori Program: {Montessori}<br />";

    var ececontent = "<b>{School}</b><br/>";
                ececontent += "Full-Day Preschool (ECE): {FourYrFullDay}<br />";                
                ececontent += "Half-Day Preschool (ECE): {FourYrHalfDay}<br />";               
                ececontent += "Full-Day Preschool (ECE) for 3 year olds: {ThreeYrFullDay}<br />";
                ececontent += "Half-Day Preschool (ECE) for 3 year olds: {ThreeYrHalfDay}<br />";
                ececontent += "Preschool (ECE) Classrooms Taught in Spanish: {SpanishTwo}<br />";
                ececontent += "Qualistar Rating: {QualistarRating}<br />";
    var kcontent = "<b>{School}</b><br/>";
                kcontent += "Full-Day Kindergarten: {FullDay}<br />";                
                kcontent += "Half-Day Kindergarten: {HalfDay}<br />";
                kcontent += "Kindergarten Programs Taught in Spanish: {Spanish}<br />";         
    var infoWindowOptionsTabs = {
        contentTabs:[{label:"Info", content:infocontent},
              {label:"ECE", content:ececontent},
              {label:"K", content:kcontent}
              ],
              selectedTab:0
      };  
      var select_html = '<select onChange="handleSelected(this)">' +
                        '<option selected> = Select a School - </option>';
                        
      function handleSelected(opt) {
        var i = opt.selectedIndex - 1;
        if (i > -1) {
            GEvent.trigger(gmarkers[i], "click");
        }
        else {
            gmap.closeInfoWindow();
        }
      } 
      
// ----------------------------INITIALIZE FUNCTION ---------------------------                              

      function initialize() {
        // GMap construction
        gmap = new GMap2(document.getElementById('gmap'));
        gmap.addMapType(G_NORMAL_MAP);
        gmap.addMapType(G_SATELLITE_MAP);
        gmap.addControl(new GLargeMapControl());
        gmap.addControl(new GMapTypeControl());

        gmap.setCenter(new GLatLng(39.72, -104.91), 11); 
        gmap.enableScrollWheelZoom();
        geocoder = new GClientGeocoder();

        //Create MapExtension utility class
        mapExtension = new esri.arcgis.gmaps.MapExtension(gmap);
          mapext = new esri.arcgis.gmaps.MapExtension(gmap);
          idtask = new esri.arcgis.gmaps.IdentifyTask("http://gistest.dpsk12.org/ArcGIS/rest/services/ECE/MapServer");
          findTask = new esri.arcgis.gmaps.FindTask("http://gistest.dpsk12.org/ArcGIS/rest/services/ECE/MapServer");

          //var dynamicMap = new esri.arcgis.gmaps.DynamicMapServiceLayer("http://gistest.dpsk12.org/ArcGIS/rest/services/ECE/MapServer", null, 0.75, dynmapcallback);

        // Query Task
        qtask = new esri.arcgis.gmaps.QueryTask("http://gistest.dpsk12.org/ArcGIS/rest/services/ECE/MapServer/0");
        bufferqtask = new esri.arcgis.gmaps.QueryTask("http://gistest.dpsk12.org/ArcGIS/rest/services/ECE/MapServer/0");
        //This query task uses the layer ElemSite Centers - which is a point layer.

        // Query Task for Neighborhood Schools 
        neighborschooltask = new esri.arcgis.gmaps.QueryTask("http://gistest.dpsk12.org/ArcGIS/rest/services/PreschoolLocator/MapServer/1");

        //Geometry service endpoint (This service is used to buffer a radius around a location)
        gsvc = new esri.arcgis.gmaps.Geometry("http://gistest.dpsk12.org/ArcGIS/rest/services/Geometry/GeometryServer");

        //this is the proxy page that will be used if the toJson payload to the geometry service is greater than 2000 characters.
        //If this is null or not available the buffer operation will not work.  
        esri.arcgis.gmaps.Config.proxyUrl = "../proxy.ashx";

        // You can execute a task and listen for the complete event or use the callback to get the results
        GEvent.addListener(qtask, "complete", function() {
        });

        // Query
        query = new esri.arcgis.gmaps.Query();
        
        //Add Listener for identify
          GEvent.addListener(gmap, "click", function(overlay,point) {
            doIdentify(overlay,point);
          });     
          
        //Add Listener for find
            GEvent.addListener(findTask, "complete", function() {
            });

         // Find Parameters
            params = new esri.arcgis.gmaps.FindParameters();
            params.layerIds = [0,1];
            params.searchFields = ["School"];   
            
        //Set the focus... so people will stop expecting the form to read your mind.
        document.getElementById("btnFind").focus();
        
      }
// ---------------------END INITIALIZE FUNCTION -------------------------------

      
      function showAllSchools(){
        mapExtension.removeFromMap(gOverlays);
        query.returnGeometry = true;
        query.outFields = ["School","website","Phone","Street","City","State","ZipCode","Principal","Montessori","HalfDay","FullDay","Spanish","ThreeYrHalfDay","ThreeYrFullDay","FourYrHalfDay","FourYrFullDay","SpanishTwo","QualistarRating"];
        query.where = "State = 'Co'";  
        qtask.execute(query, false, mycallback);                     
      }
      


//------------------------------SEARCH -----------------------------------------      

      function executeFind(searchText) {
            // clear map overlays and event listeners using MapExtension removeFromMap
            //This function searches through the elementary school layer.
            mapExtension.removeFromMap(gOverlays);
            gmap.setCenter(new GLatLng(39.72, -104.91), 11); 
            if (searchText == "") {
                alert("Please enter a school name to search for");
                return;
            }
            
            gmap.clearOverlays();
            document.getElementById('results').innerHTML = '';

            // set find parameters
            params.searchText = searchText;

            // execute find task
            findTask.execute(params, function(featureSet, error) {
              if (error) {
                alert("Error " + error.code + ": " + (error.message || (error.details && error.details.join(" ")) || "Unknown error" ));
                return;
              }
             findCompleteCallback(featureSet);
             });             

      }

      function findCompleteCallback(featureSet) { 
      //This function is the callback to ExecuteFind function
      
      var findResults = featureSet.findResults, findResult, geometry, attributes, geom, i, j, name, foundField;
      var uniqueId = 0;
      var table = "<table><tr><th><h3>Schools matching Search:</h3></th></tr>";
      listOfOverlays = [];
      
        //The following alphabetizes the array
        findResults.sort(function(a,b){
            var aString = a.feature.attributes.School;
            var bString = b.feature.attributes.School;
            
            if (aString < bString) return -1;
            else if (aString > bString) return 1;
            else return 0;
        });      
      
      for (i=0; i<findResults.length; i++) {  //process each result in the response
        findResult = findResults[i];
        geometry = findResult.feature.geometry;
        attributes = findResult.feature.attributes;
        name = findResult.layerName;
        foundField = findResult.foundFieldName;
        latlng = findResult.feature.latlng;
        
        if (findResult.layerId == 0) {  //This highlights the actual shape file
            var overlayOptions = {
                strokeColor: "#FF0000", strokeWeight: 3, strokeOpacity: 0.55,
                fillColor: "#000066", fillOpacity: 0.4
            };                   
            var gOverlay = mapext.addToMap(findResult, overlayOptions, infoWindowOptionsTabs);
            //var ov = mapext.addToMap(idresults, overlayOptions, infoWindowOptionsTabs);
            
        }  
        else {    //This is to add the info to the table and zoom into the school site (this uses the point file)
                    
            //add a row to the table
            table = table + "<tr><td>"
                + "<a href='#' onclick='showInfoWindow(" + uniqueId + ")'>" 
                + attributes[foundField] + "</a></td></tr>";
        
            for (j=0; j<geometry.length; j++) { //Feature.geometry is an array of GPolygon/GMarker
                geom = geometry[j];
                          
                //setup the click event listener for overlay
                var func = getClickFunc(attributes, findResult.layerId, name, foundField);
                GEvent.addListener(geom, "click", func);
            
                //add overlay to map
                gmap.addOverlay(geom);
            
                //maintain a list of overlays and their associated click listener function
                //used later when hyperlink is clicked
            
                listOfOverlays[uniqueId++] = { "overlay": geom, "func": func };
            }
         }
      }   
      //show the table of results
      table = table + "</table>";
      document.getElementById('results').innerHTML = table;         
    } 

    
    function getClickFunc(attributes, layerId, layerName, foundFieldName) {
        var content = "<div style='height:130px; width:310px'>";
            content += "<strong>" + attributes["School"] + "</strong><br />";
            content += attributes["Street"] + "<br />";
            content += attributes["City"] + ",&nbsp;" + attributes["State"];
            content += "&nbsp;&nbsp;" + attributes["ZipCode"] + "<br />";
            content += attributes["Phone"] + "<br />";
            content += "Principal: " + attributes["Principal"] + "<br />";
            content += "<a href='" + attributes["website"] + "'>School Website</a><br />";
            content += "Montessori Program: " + attributes["Montessori"] + "<br />";
   
        var labels=[];
        var ececontent = "<strong>" + attributes["School"] + "</strong><br />";
            ececontent += " Full-Day Preschool (ECE): " + attributes["FourYrFullDay"];
            ececontent += "<br /> Half-Day Preschool (ECE): " + attributes["FourYrHalfDay"];
            ececontent += "<br /> Full-Day Preschool (ECE) for 3 year olds: " + attributes["ThreeYrFullDay"];
            ececontent += "<br /> Half-Day Preschool (ECE) for 3 year olds: " + attributes["ThreeYrHalfDay"];
            ececontent += "<br /> Preschool (ECE) Classrooms Taught in Spanish: " + attributes["SpanishTwo"];
            ececontent += "<br /> Qualistar Rating: " + attributes["QualistarRating"];  
        var kcontent = "<strong>" + attributes["School"] + "</strong><br />";
            kcontent += "Full-Day Kindergarten: " + attributes["FullDay"];
            kcontent += "<br /> Half-Day Kindergarten: " + attributes["HalfDay"];
            kcontent += "<br /> Kindergarten Programs Taught in Spanish: " + attributes["Spanish"];
            labels = ["Info", "ECE", "K"];
            
            var htmls=[];
            htmls=[content, ececontent, kcontent];
            
            if (htmls.length > 2) {
                htmls[0] = '<div style="height:130px; width:' + htmls.length*90 + 'px">' + htmls[0] + '</div>';
            }
            var tabs = [];
            for (var i=0; i<htmls.length; i++){
                tabs.push(new GInfoWindowTab(labels[i],htmls[i]));
            }  
        
        return function(latlng) { 
            gmap.openInfoWindowTabsHtml(latlng, tabs);
        }
        
    }
  
    
// -----------------------------END SEARCH --------------------------------  
  
    function showInfoWindow(uniqueId) { //function to be called when user clicks on link
        var polygon = listOfOverlays[uniqueId].overlay;
        var func = listOfOverlays[uniqueId].func;
        
        //center and zoom to polygon
        var bounds = polygon.getBounds();
        var center = bounds.getCenter();
        //var zoomLevel = gmap.getBoundsZoomLevel(bounds);
        gmap.setCenter(center, 14);
        
        //show info window
        func(center);
    }
    
    function showInfoWindowPoint(uniqueId) { //function to be called when user clicks on link
        var polygon = listOfOverlays[uniqueId].overlay;
        var func = listOfOverlays[uniqueId].func;
        
        //center and zoom to polygon
        var center = polygon.getLatLng();
        //var zoomLevel = gmap.getBoundsZoomLevel(bounds);
        gmap.setCenter(center, 14);
        
        //show info window
        func(center);
    }    
    
    function clearResults(){
        mapext.removeFromMap(ovs);
        mapext.removeFromMap(gOverlays);
    }   
    function dynmapcallback(groundov) {
          //Add groundoverlay to map using gmap.addOverlay()
          gmap.addOverlay(groundov);
          dynMapOv = groundov;
    }
    
// ------------------------IDENTIFY -------------------------------------    

    function doIdentify(overlay, point) {
            // If there is already an overlay... open Infowindow
          if (overlay) {
            return;
          }
          var dim = gmap.getSize();
          var idparams = new esri.arcgis.gmaps.IdentifyParameters();
          idparams.geometry = point;
          idparams.tolerance = 8;
          idparams.bounds = gmap.getBounds();
          idparams.width = dim.width;
          idparams.height = dim.height;
          idparams.layerIds = [0,1];
          idparams.layerOption = "all";
          idtask.execute(idparams, idcallback);
    }
    
    function idcallback(idresults, point) {
        //turns clicked on school red and opens infowindow
          var overlayOptions = {
            strokeColor: "#FF0000", strokeWeight: 3, strokeOpacity: 0.55,
            fillColor: "#000066", fillOpacity: 0.4
          };

          var ov = mapext.addToMap(idresults, overlayOptions, infoWindowOptionsTabs);

          for (var x = 0; x < ov.length; x++) {
            ovs.push(ov[x]);
          }
          
    }  
//------------------------------END IDENTIFY ------------------------------------       
