﻿//-----------------------------FIND ADDRESS - GEOCODE ----------------------------

    function findAddress(address) {
     //Clear the map
     gmap.clearOverlays();
     //Display all schools with red markers first
     showAllSchools();  
     
     //Add Denver, CO to address, in order for Google to Geocode properly
      address = address + " Denver, CO";
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
              gmap.setCenter(point, 14);
              //the following makes a white icon that will be used to mark the address
              var iconOptions = {}; 
              iconOptions.width = 32; 
              iconOptions.height = 32; 
              iconOptions.primaryColor = "#FFFFFF"; 
              iconOptions.cornerColor = "#AAAAAA"; 
              iconOptions.strokeColor = "#000000"; 
              var icon = MapIconMaker.createMarkerIcon(iconOptions);
              //mark the address location with the white marker
              marker = new GMarker(point, {icon:icon, title:address});
              gmap.addOverlay(marker);

                neighborhood = new esri.arcgis.gmaps.Query();
                //set neighborhood school search parameters
                neighborhood.queryGeometry = point;
                neighborhood.outFields = ["ELM_SCHOOL","ELEM_ID"];
                neighborschooltask.execute(neighborhood, false, myneighborhoodcallback);
                                           
              text = address + "<br /><h4>Your neighborhood Preschool and Kindergarten School is ";
            }
          }
          
        ); 
      }
    }
    
    function myneighborhoodcallback(fset) {
       
        fe = fset.features;
        attributes = fe[0].attributes;
        //Get the neighborhood school number for later use.
        neighborhoodschoolnumber = attributes["ELEM_ID"];
        //gOverlays = mapExtension.addToMap(fset,overlayOptions,infoWindowOptions3);
        text = text + "<b>" + attributes["ELM_SCHOOL"] + "</b></h4>";  
        //text = text + table;      
        //marker.openInfoWindowHtml(text);
        //query the point layer to determine location of neighborhood school
        neighborhoodschool = new esri.arcgis.gmaps.Query();
        neighborhoodschool.outFields = ["School","website","Phone","Street","City","State","ZipCode","Principal","Montessori","HalfDay","FullDay","Spanish","ThreeYrHalfDay","ThreeYrFullDay","FourYrHalfDay","FourYrFullDay","SpanishTwo","QualistarRating"];
        neighborhoodschool.where = "SchoolID = '" + neighborhoodschoolnumber + "'";
        neighborhoodschool.returnGeometry = true;
        qtask.execute(neighborhoodschool, false, displayneighborhoodschool);  
        document.getElementById('topresults').innerHTML = text;         
        return neighborhoodschoolnumber;    
    }
    
    function displayneighborhoodschool(fset){
  
        
        //Then display neighborhood school marker blue on top!!!!!
        
    var findResults = fset.features, findResult, geometry, attributes, geom, i, j, name, foundField;
        listOfOverlays = [];    

        findResult = findResults[0];
        geometry = findResult.geometry;
        attributes = findResult.attributes;
        name = findResult.layerName;
        foundField = findResult.foundFieldName;
        geom = geometry[0];
        var addresspoint = geom.getLatLng();

        //setup the click event listener for overlay on marker of neighborhood school
        var func = getClickFunc(attributes, findResult.layerId, name, foundField);
        
        
        //Create a starred icon that is blue       
        var newIcon = MapIconMaker.createLabeledMarkerIcon({addStar: true, label: " ", primaryColor: "#0000ff", height:50});
        //Place the starred icon as a marker at the school location
        var marker = new GMarker(geom.getLatLng(), {icon: newIcon});
        //Add a listener, so that a click on the marker opens the infowindow. 
        GEvent.addListener(marker, "click", func);      
        //add overlay to map
        gmap.addOverlay(marker);        
       
        // Build the html that will go in the info windows
        var content = "<div style='height:200px; width:310px'>";
            content += "<h4>Your Neighborhood School is <br /></h4>";
            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:150px; width:' + htmls.length*90 + 'px">' + htmls[0] + '</div>';
            }
            var tabs = [];
            for (var k=0; k<htmls.length; k++){
                tabs.push(new GInfoWindowTab(labels[k],htmls[k]));
            }  
   
        marker.openInfoWindowTabsHtml(tabs);
        
        /*
        //And display all other ECE schools within 5 mile radius (Called a buffer)
        //The following needs to occur
        // 1.  Address location determined.. (already found above addresspoint)
        // 2.  Buffer operation occurs
        // 3.  Buffer complete event fires
        // 4.  Query task executes
        // 5.  Query execute complete event fires and rest of schools are displayed
       
        //Listen for querytask execute complete event
        GEvent.addListener(qtask, "executecomplete", function(fset) {
            mapExtension.addToMap(fset);
            text = text + "<br />Other schools within 5 miles of your address include: ";
            text = text + "<br />";
            text = text + buildListofSchools(fset);
            document.getElementById('results').innerHTML = text;        
        });       
        
        //Query
        var query = new esri.arcgis.gmaps.Query();
        query.returnGeometry = true;
        query.outFields = ["School", "Montessori", "website"];    
        
                  
        //buffer parameters
        var buffParams = new esri.arcgis.gmaps.BufferParameters();
        buffParams.unit = esri.arcgis.gmaps.SRUnitType.FOOT;
        buffParams.unionResults = true;  //default is false
        buffParams.distances = 5280; //5 mile buffer (in feet)
         //******************This is where the address point needs to go
        
        //Listen for buffercomplete event
        
        GEvent.addListener(gsvc, "buffercomplete", function(results) {
            var bufferPolys=[];
            for (var x = 0; x <results.geometries.length; x++){
                for (var y=0; y <results.geometries[x].length; y++){
                    bufferPolys.push(results.geometries[x][y]);
                }
            }
            query.queryGeometry = bufferPolys;
            //query.
            qtask.execute(query);
            mapExtension.addToMap(results);
         });
          
         //Listen for mapclick
         GEvent.addListener(gmap, "click", function(marker, point){
            if (marker){return;}
            else if (!point) {return;}
            else {
                //gmap.clearOverlays();
                buffParams.geometries = [point]; 
                gsvc.buffer(buffParams);
            }
         }); 
    }
    function buildListofSchools(fset) {
        var features = fset.features;
        for (var x = 0; x < features.length; x++){
            text = text + features[x].attributes['website'];
        }
        return text; */
    }
   
//-----------------------------END FIND ADDRESS - GEOCODE ----------------------------
    