﻿// JScript File

     var map = null;
     var geocoder = null;
     var gdir = null;
     var gmarkers = [];
     var cboloclst = "";  //Store return string when results are > 26.
     
     var ovrtab = [];     //Array for storing overview description.  Used to display overview on infowindow.
     var dsctab = [];     //Array for storing details description.  Used to display description on infowindow.
     var ovrTblDes = [];  //Array for storing overview w/o direction text.  Used to display over on table listing below the map.
     
     // arrays to hold variants of the info window html with get direction forms open      
     var to_htmls = [];
     var from_htmls = []

     //Load all the parameters necessary to use Google maps.
     function onLoad() {
     
       var browserName=navigator.appName; 
       var extraSpaceForFooter=50;
       if (!(browserName=="Microsoft Internet Explorer"))
        {
         extraSpaceForFooter=90;
         alert("This website has been optimized for Internet Explorer.  You are using " + browserName + " so you may experience display problems.");
        }

        //Top of panels and map div.  Change to reflect spacing of headers.
          var toppos = 160
//        document.getElementById("map").style.top = toppos;
//        document.getElementById("divPnlSearch").style.top = toppos;
//        document.getElementById("divPnlResults").style.top = toppos;
        
        //Set map height and width based on browser size.
        var hght=document.documentElement.clientHeight - 150 - toppos;
        var wdth=document.documentElement.clientWidth*0.745;
        document.getElementById("map").style.height=hght+"px";
        document.getElementById("map").style.width=wdth+"px";
        var mapt = document.getElementById("map").style.top;
        var maph = document.getElementById("map").style.height;        
        var dlpos = toppos + Number(mapt.substring(0,(mapt.indexOf("px"))))+Number(maph.substring(0,(maph.indexOf("px"))))+"px";
        document.getElementById("datalist").style.top=dlpos;
        document.getElementById("datalist").style.height="100px";
        document.getElementById("datalist").style.width=document.documentElement.clientWidth+"px";
          
        //Set panel heights based on browser size.
        var dlhgt = document.getElementById("datalist").style.height;
        var divhgt = Number(dlhgt.substring(0,(dlhgt.indexOf("px"))))+Number(maph.substring(0,(maph.indexOf("px"))));     
        var footertop = 100 + toppos + Number(mapt.substring(0,(mapt.indexOf("px"))))+Number(maph.substring(0,(maph.indexOf("px"))));
        document.getElementById("divPnlSearch").style.height=divhgt+50+"px";
        document.getElementById("divPnlResults").style.height=divhgt+50+"px";
        document.getElementById("pnlResults").style.height=hght+50+"px";
        document.getElementById("pnlSearch").style.height=hght+50+"px";
        document.getElementById("footspacerrow").style.height=hght+extraSpaceForFooter+"px";
         
        show('pnlSearch');
        try
        {
        var compat = GBrowserIsCompatible();
        }
        catch(err){alert("Google Maps is unavailable or incompatable with your browser");}
       
        if (GBrowserIsCompatible()) { 
          if (!map) {
              map = new GMap2(document.getElementById("map"));  //Create the Google map object.
              map.setCenter(new GLatLng(37.70, -121.93), 10); //Center map on East Bay area
              map.addControl(new GSmallMapControl());           //Add large zoom/pan tool to map
              map.addControl(new GMapTypeControl());            //Add Map type options (Street, Satellite, Hybrid) to map.
              geocoder = new GClientGeocoder();                 //Get things ready to geocode.            
              window.setTimeout(MarkerLoad, 0);                 //Load CBO markers

              // === create a GDirections Object ===
              gdir=new GDirections(map, document.getElementById("pnlResults"));

              // === Array for decoding the failure codes ===
              var reasons=[];
              reasons[G_GEO_SUCCESS]            = "Success";
              reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
              reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
              reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
              reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
              reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
              reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
              reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
              reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
              reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

              // === catch Directions errors ===
              GEvent.addListener(gdir, "error", function() {
                var code = gdir.getStatus().code;
                var reason="Code "+code;
                if (reasons[code]) reason = reasons[code]; 
                alert("Failed to obtain directions, "+reason);
               });
               
               // ====== Restricting the range of Zoom Levels =====
               // Get the list of map types      
               var mt = map.getMapTypes();
               // Overwrite the getMinimumResolution() and getMaximumResolution() methods
               for (var i=0; i<mt.length; i++) {
                 mt[i].getMinimumResolution = function() {return 10;}
               }
               // Add a move listener to restrict the bounds range
               GEvent.addListener(map, "move", function() {
                checkBounds();
               });
            }
           
        
        } else {
            alert("Sorry, the Google Maps API is not compatible with this browser");
        }
    }

      // If the map position is out of range, move it back
      function checkBounds() {
        // The allowed region which the whole map must be within
        var allowedBounds = new GLatLngBounds(new GLatLng(37.4,-122.40), new GLatLng(38.0,-121.45));
        
        // Perform the check and return if OK
        if (allowedBounds.contains(map.getCenter())) {
          return;
        }
        
        // It`s not OK, so find the nearest allowed point and move there
        var C = map.getCenter();
        var X = C.lng();
        var Y = C.lat();

        var AmaxX = allowedBounds.getNorthEast().lng();
        var AmaxY = allowedBounds.getNorthEast().lat();
        var AminX = allowedBounds.getSouthWest().lng();
        var AminY = allowedBounds.getSouthWest().lat();

        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}
        
        map.setCenter(new GLatLng(Y,X));
      }
      
    //Open the weblink in the Infowindows in a separate browser.
    function openWebLink(url) {
        window.open(url, "win")
    }
    
    //Clear all the search options on the form.
    function ResetAll() {
        document.getElementById("AddressField").value = "";
        document.getElementById("ddlCityList").value = "";
        document.getElementById("ddlCBOName").value = "";
        
        //Clear all the markers
        map.clearOverlays();
        
        //Reload CBO markers
        window.setTimeout(MarkerLoad, 0);
        
        Check_UnCheckAllServices("cblServices", false);
    }
    
    //Check or uncheck all checkboxes on the service list based on "Chk" variable.    
    function Check_UnCheckAllServices(ID, Chk){
    
        // Get the checkboxlist object.
        objCtrl = document.getElementById(ID);
        
        // Does the checkboxlist not exist?
        if(objCtrl == null) return;

        // Loop through each checkbox and check or uncheck it based on "Chk" variable.
        var c = objCtrl.getElementsByTagName("input");
        for (var i=0;i<c.length;i++)
        {
            if (c[i].checked==(!Chk)) c[i].checked=Chk;
        }   

    }

    //Trap the form submit that the input keypress wants to do.
    function trapEnterkey() {      
      if (window.event && window.event.keyCode == 13) {
        SearchMap();
        return false;
       } else {
        return true;
      }  
    }
    
    //Show or hide the search and results panels
    function show(id){

        if (id=='pnlSearch') {
            document.getElementById('pnlSearch').Visible='true';
            document.getElementById('divPnlSearch').style.visibility='visible'
            document.getElementById('pnlResults').Visible='false';
            document.getElementById('divPnlResults').style.visibility='hidden';
            document.getElementById('searchtd').style.backgroundColor='#ffeac6';
            document.getElementById('resultstd').style.backgroundColor='#eee';
            
        } else {
            document.getElementById('pnlSearch').Visible='hidden';
            document.getElementById('divPnlSearch').style.visibility='hidden'
            document.getElementById('pnlResults').Visible='visible';
            document.getElementById('divPnlResults').style.visibility='visible';
            document.getElementById('searchtd').style.backgroundColor='#eee';
            document.getElementById('resultstd').style.backgroundColor='#ffeac6';     
        }    
    } 
    
    //Concat the service list checkbox values together so the app can process them.
    function ConcatServLst(ID) {
        // Get the checkboxlist object.
        objCtrl = document.getElementById(ID);
        
        // Does the checkboxlist not exist?
        if(objCtrl == null) return;

        // Loop through each checkbox and check or uncheck it based on "Chk" variable.
        var c = objCtrl.getElementsByTagName("input");
        var lst="";
        for (var i=0;i<c.length;i++)
        {
            if (c[i].checked==(true)) {
                if (lst=="") {
                    lst = i;
                } else {
                    lst = lst+"|"+i;
                }
            }       
        }
        
        return lst;
    }

    function SetFieldDisplay(field) {
        if (field=='ADDRESS') {
            document.getElementById("ddlCityList").value = "";
            document.getElementById("ddlCBOName").value = "";
        }
        if (field=='CITY') {
            document.getElementById("AddressField").value = "";
            document.getElementById("ddlCBOName").value = "";
        }
        if (field=='NAME') {
            document.getElementById("AddressField").value = "";
            document.getElementById("ddlCityList").value = "";
        }
    }
    
          // ===== request the directions =====
      function getDirections() {
        var saddr = document.getElementById("saddr").value
        var daddr = document.getElementById("daddr").value
        gdir.load("from: "+saddr+" to: "+daddr);
      }
      
      function SendEmail() {
        var address = "keith.palmer@westonsolutions.com";
        var url = "mailto:" + "keith.palmer" + "@" + ".westonsolutions.com";

        document.write("<a href=\"" + url + "\">" + address + "</a>");
      }
