// JScript File    
// Google Maps API JS

    // Initial Variables
    var map = null;
    var geocoder = null;
    var mapLoaded = false ;
    // Initial Points to Load
    var initialResults = new Array(10) ;
    var initialPoints  = new Array(10) ;
    // Initialize the Load Points
    for (var i = 0; i < 10; i++) {
         initialPoints[i]="";
    }    
    for (var i = 0; i < 10; i++) {
         initialResults[i]="";
    }            
    var pointIndex = -1 ;
    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    //////////////////////////////////////////////////////////////////
    var baseIcon = new GIcon();    
    var mapMode  = "MAP";
    var startingAddress = "" ;
    //////////////////////////////////////////////////////////////////
    var directionsPanel;
    var directions;       
    var bounds = new GLatLngBounds();      
   ////////////////////////////////////////////////////////////////// 
   function toggleOpen(target) {
	 obj=document.getElementById(target);
	 obj.style.display= '';
   }
   
   function toggleClose(target) {
	obj=document.getElementById(target);
	obj.style.display= 'none';
   }
   function toggle(target) {
	obj=document.getElementById(target);
	obj.style.display=( (obj.style.display=='none') ? '' : 'none');
   }    
   //////////////////////////////////////////////////////////////////  
   
    //////////////////////////////////////////////////////////////////
    //
    function loadBaseIcon() {
	    baseIcon.shadow = AppRoot + "/common/images/shadow.png";
	    baseIcon.iconSize = new GSize(28, 35);
	    baseIcon.shadowSize = new GSize(33, 19);
	    baseIcon.iconAnchor = new GPoint(13, 35);
	    baseIcon.infoWindowAnchor = new GPoint(9, 2);
	    baseIcon.infoShadowAnchor = new GPoint(30, 25);    
    }
    //////////////////////////////////////////////////////////////////
    // Get& Load Directions between two address
    function getDirections(address1,address2) {
         if (mapMode=="DIRECTIONS") {
      	   //var dLink = document.getElementById("dLink");
	       //dLink.innerHTML = "Show Driving Directions";
	       toggleClose("route");
	       toggleOpen("DivDir");
	       toggleClose("DivMap");
	       
	       mapMode = "MAP";	           
	       directions.clear()
           if (initialPoints[0]!="") {           
              if (pointIndex>-1)
                showAddress(initialPoints[0],pointIndex,true,initialResults[0]);
              else
                showAddress(initialPoints[0],0,true,initialResults[0]);
           }
                  
         } else {    
             if ((address1!="") && (address2!="")) {
                 map = new GMap2(document.getElementById("map"));
                 directionsPanel = document.getElementById("route");
                 if ((map!=null) && (directionsPanel!=null)) {
                    directions = new GDirections(map, directionsPanel);
                    GEvent.addListener(directions, "load", onGDirectionsLoad);
                    GEvent.addListener(directions, "error", handleErrors);      
                    directions.load("from: " + address1 + " to: " + address2);
                 }     
             } else {
                alert("Directions not available!");
             }
         }
        }
         
    //////////////////////////////////////////////////////////////////
        
    ///////////////////////////////////////////////////////////////////
    // Create a point marker with base icon class
    function createMarker(point, index, markerText) {
          var letter = String.fromCharCode("A".charCodeAt(0) + index);
          var icon = new GIcon(baseIcon);
          icon.image = AppRoot + "/common/images/tab" + letter + ".png";
          var marker = new GMarker(point, icon);
          if (markerText!="") {
            GEvent.addListener(marker, "click", function() {
              marker.openInfoWindowHtml(markerText);
            });
          }
          return marker;
    }    
    ///////////////////////////////////////////////////////////////////
    
    ///////////////////////////////////////////////////////////////////
    // Initialize Map Object and Load initial Points
    function load() {    
          loadBaseIcon();
          if (window.loadPoints)
              loadPoints();
          if (GBrowserIsCompatible()) {            
            if (document.getElementById("map")!=null) {
                map = new GMap2(document.getElementById("map"));
                map.addControl(new GSmallMapControl());
                map.addControl(new GMapTypeControl());
                geocoder = new GClientGeocoder();                
                for (var i = 0; i < 10; i++) {
                 if (initialPoints[i]!="") {
                       if (pointIndex>-1)
                          showAddress(initialPoints[i],pointIndex,true,initialResults[i]);
                       else
                          showAddress(initialPoints[i],i,true,initialResults[i]);
                     }
                }
                
                if (window.opener!=null)
                  if (window.opener.mapMode!=null)
                    if (window.opener.mapMode=="DIRECTIONS")
                         getDirections(startingAddress,initialPoints[0])
                       
            }
          }
    }
    ///////////////////////////////////////////////////////////////////          
    
    ///////////////////////////////////////////////////////////////////
    // Create marker for single address on Map
    function showAddress(address,index,setMarker,markerText) {
          if (geocoder) {                 
            geocoder.getLatLng(
              address,
              function(point) {
                if (!point) {
                  // alert(address + " not found");
                  if (index==0) {
              	   var dLink = document.getElementById("DivDir");
               	   if (dLink!=null)  {
               	       toggleClose("DivDir");
               	       toggleClose("DivMap");
               	       }
	                  //dLink.innerHTML = "";              	       	                                                  
                  }
                } else {                          
                   //map.setCenter(point, 13);
                   bounds.extend(point); 
                   map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds)); 
                   if (setMarker==true) {
                     var marker = createMarker(point, index, markerText ) ; //new GMarker(point);              
                     map.addOverlay(marker);
                     map.setZoom(map.getBoundsZoomLevel(bounds));
                     map.setCenter(bounds.getCenter());                                                          
                     //map.addOverlay(new GMarker(point));
                     //marker.openInfoWindowHtml(address);
                   }
                   
                }
              }
            );
          }
    }
    ///////////////////////////////////////////////////////////////////


    ///////////////////////////////////////////////////////////////////
    // Error Handler
    function handleErrors(){
	   if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code);
	   else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);
	   
	   else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);

	// else if (directions.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//   alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + directions.getStatus().code);
	     
	   else if (directions.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);

	   else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}
	///////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////
    // Handler for Directions Load
	function onGDirectionsLoad(){ 
	  //var dLink = document.getElementById("dLink");
	  //dLink.innerHTML = "Show on Map";
	  mapMode = "DIRECTIONS";	  
	  toggleOpen("route");
	  toggleClose("DivDir");
	  toggleOpen("DivMap");
	  document.forms[0].routeSummary.value = escapeHTML (getRouteSummary());
	}
    ///////////////////////////////////////////////////////////////////
    
    ///////////////////////////////////////////////////////////////////
    // Parse Route Data    
    function getRouteSummary() {
       var route ;
       var step  ;
       
       var directionsummary = "<b>Summary:</b>&nbsp;" + directions.getSummaryHtml() ;
       route = directions.getRoute(0);
       for (var i = 0; i < route.getNumSteps(); i++) {        
         step = route.getStep(i);         
         directionsummary = directionsummary + "<br><b>" +  (i+1) +  ".</b>&nbsp;"  +  step.getDescriptionHtml();
       }

       directionsummary = "<br><b>From:</b>" + startingAddress + "<br><b>To:</b> " +  initialPoints[0] + "<br><br>" + directionsummary 
       return directionsummary ;       
    }
  
    function escapeHTML (str)
    {
    var div = document.createElement("div");
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;

    }
    ///////////////////////////////////////////////////////////////////
    
    
    ///////////////////////////////////////////////////////////////////
    // Validation function Terms checkbox    
    function DoctorLocatorTermsValidate(source, args)
    {         
            if(document.getElementById('ctl00_ContentPlaceHolder1_PhysicianSearch1_Terms')!=null)
            {
                args.IsValid = document.getElementById('ctl00_ContentPlaceHolder1_PhysicianSearch1_Terms').checked ;
            }
            else
            {
                args.IsValid = false;
            }  
    }            
    ///////////////////////////////////////////////////////////////////\
