﻿// ----------------------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 dynamicMap;
    
    
    var infocontent = "<div style='height:130px; width:310px'>";
        infocontent += "<b>";

      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();
        //geocoder = new google.maps.Geocoder();

        //Create MapExtension utility class
        mapExtension = new esri.arcgis.gmaps.MapExtension(gmap);
          mapext = new esri.arcgis.gmaps.MapExtension(gmap);
          findTask = new esri.arcgis.gmaps.FindTask("http://gis.dpsk12.org/ArcGIS/rest/services/Boundaries0910/MapServer");

          var dynamicMap = new esri.arcgis.gmaps.DynamicMapServiceLayer("http://gis.dpsk12.org/ArcGIS/rest/services/Boundaries0910/MapServer", null, 0.5, dynmapcallback);
          dynamicMap.setVisibleLayers([0,1]);
         
        // Query Task
        qtask = new esri.arcgis.gmaps.QueryTask("http://gis.dpsk12.org/ArcGIS/rest/services/Boundaries0910/MapServer/0");
        bufferqtask = new esri.arcgis.gmaps.QueryTask("http://gis.dpsk12.org/ArcGIS/rest/services/Boundaries0910/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://gis.dpsk12.org/ArcGIS/rest/services/Boundaries0910/MapServer/1");
        transportationzonetask = new esri.arcgis.gmaps.QueryTask("http://gis.dpsk12.org/ArcGIS/rest/services/Boundaries0910/MapServer/16");
        

        //Geometry service endpoint (This service is used to buffer a radius around a location)
        gsvc = new esri.arcgis.gmaps.Geometry("http://gis.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 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 getClickFunc(attributes, layerId, layerName, foundFieldName) {

        var tabs = buildWindow(attributes);
                
        return function(latlng) { 
            gmap.openInfoWindowTabsHtml(latlng, tabs);
        }
        
    }
  
    
// ----------- The following functions open the InfoWindow for the bubbles
  
    function showInfoWindow(schoolId) { //function to be called when user clicks on link
        //perform a query to find schoolId
        
        var squery = "Number = '" + schoolId + "'";
        query.returnGeometry = true;
        query.where = squery;
        query.outFields="*";
        qtask.execute(query, false, querycallback);
            

    }
    function querycallback(fset){
        var attributes = fset.features[0].attributes;     
        var latlng = fset.features[0].geometry[0].getPoint();
        var tabs = buildWindow(attributes);
     
        gmap.openInfoWindowTabsHtml(latlng, tabs);
    
    }
    
    
    function showInfoWindowPoint(lat,lng,uniqueId) { //function to be called when user clicks on link from list of schools
        var polygon = listOfOverlays[uniqueId].overlay;
        var func = listOfOverlays[uniqueId].func;
        
        //center and zoom to polygon
        //var zoomLevel = gmap.getBoundsZoomLevel(bounds);
        gmap.setCenter(new GLatLng(lat,lng), 14);
        
        //show info window
        func(new GLatLng(lat,lng));
    }    

// ------------ CLEAR ALL LAYERS
    
    function clearResults(){
        mapext.removeFromMap(ovs);
        mapext.removeFromMap(gOverlays);
    }   
    
    function dynmapcallback(groundov) {
          //Add groundoverlay to map using gmap.addOverlay()
          gmap.addOverlay(groundov);
          dynMapOv = groundov;
    }
    
    function buildWindow(attributes){
            var content = "<div style='height:130px; width:310px'>";
            content += "<strong>" + attributes["schoolname"] + "</strong><br />";
            content += attributes["address"] + "<br />";
            content += "Denver, CO" ;
            content += "&nbsp;&nbsp;" + attributes["zip"] + "-" + attributes["zip4"] + "<br />";
            content += "(" + attributes["areacode"] + ") " + attributes["phone"] + "<br />";
            content += "Fax: (" + attributes["faxareacode"] + ") " + attributes["fax"] + "<br />";
            content += "Principal: " + attributes["principal"] + "<br />";
            content += "<a href='" + attributes["url"] + "'>School Website</a><br />";
   
        var labels=[];
        var morecontent = "<strong>" + attributes["schoolname"] + "</strong><br />";
        morecontent += "Grades served: " + attributes["gradelevel"] + "<br />";
        morecontent += "High School transporation is provided by RTD for eligible students.<br /><a href='http://rtd-denver.com'>Click here for RTD Trip Planner</a>";

            labels = ["Info", "More"];
            
            var htmls=[];
            htmls=[content, morecontent];
            
            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 tabs;
    
    }