﻿			var map;
			var gdir;
			// The current (GMarker) location of the virtual "car"
			var currentLocation;
			// Array of GMarker objects to contain all of the locations/stores of interest
			var markerArray;
			// GPolygon object that represents the area of interest within a specific radius of the virtual car
			var polygon;
			// "Radius" (so to speak) around the virtual car.  The polygon is not an true circle, so the radius is an estimated distance around the car.
			var radiusInMiles;
			// An estimated number of miles per latitude segment (see the GPolygon.prototype.Contains method below)
			var milesPerLat = 69.047;
			// An estimated number of miles per longitude segment (see the GPolygon.prototype.Contains method below)
			var milesPerLng = 53;
			// Value that defines how quickly the car moves across the map, in seconds
			var timeStepSecs = 1;
			// Javascript timer object created by the setTimeout function
			var motionTimer;
			// Value that defines how far the virtual car travels in each time segment, in miles
			var deltaDistance = 0.035;
			// Direction (compass) in which the virtual car will travel
			var direction;
			// Google Spreadsheet key
			var param_ssKey = "o00714943191012983869.550012061068570671";
			// Google Spreadsheet worksheet ID
			var param_wsId = "od5";
			// Starting point of the map
			var startPoint = new GLatLng(51.182812, -109.835341);
			var sidearef = new Array();
			var geocoder = new GClientGeocoder(); 
		
      var bounds = new GLatLngBounds();
			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[403]                      = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";
      reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully Loaded.";
      reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
      reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Please Enter the Address.";
      
      
      
      var patlabel=[];
      patlabel["c"]="This provider offers counseling services for alcohol dependent patients in recovery";
      patlabel["m"]="This provider can prescribe medications and oversee medical therapy for patients in recovery";
      patlabel["i"]="VIVITROL Injection Providers";
      patlabel["cm"]="This provider offers counseling and can prescribe medications and oversee medical therapy for patients in recovery";
      patlabel["mi"]="This provider can prescribe medications and oversee medical therapy for patients in recovery";
      patlabel["cmi"]="This provider offers counseling and can prescribe medications and oversee medical therapy for patients in recovery";
      patlabel["none"]="";
      
      var hcplabel=[];
      hcplabel["c"]="Psychosocial Counseling Providers";
      hcplabel["m"]="Medical Management Providers";
      hcplabel["i"]="VIVITROL Injection Providers";
      hcplabel["cm"]="Provider Offering C and M of the C-M-I Services";
      hcplabel["mi"]="Provider Offering M and I of the C-M-I Services";
      hcplabel["cmi"]="Provider Offering All Three of the C-M-I Services";
      hcplabel["none"]="";
      
      var hcpicon=[];
      hcpicon["c"]="<img src='/providerlocator/images/c.jpg' alt=\"Psychosocial Counseling Providers\" title=\"Psychosocial Counseling Providers\" border=\"0\"/>";
      hcpicon["m"]="<img src='/providerlocator/images/m.jpg' alt=\"Medical Management Providers\" title=\"Medical Management Providers\" border=\"0\"/>";
      hcpicon["i"]="<img src='/providerlocator/images/i.jpg' alt=\"VIVITROL Injection Providers\" title=\"VIVITROL Injection Providers\" border=\"0\"/>";
      hcpicon["cm"]="<img src='/providerlocator/images/cm.jpg' alt=\"Provider Offering C and M of the C-M-I Services\" title=\"Provider Offering C and M of the C-M-I Services\" border=\"0\"/>";
      hcpicon["mi"]="<img src='/providerlocator/images/mi.jpg' alt=\"Provider Offering M and I of the C-M-I Services\" title=\"Provider Offering M and I of the C-M-I Services\" border=\"0\"/>";
      hcpicon["cmi"]="<img src='/providerlocator/images/cmi.jpg' alt=\"Provider Offering All Three of the C-M-I Services\" title=\"Provider Offering All Three of the C-M-I Services\" border=\"0\"/>";
      hcpicon["none"]="";

      var paticon=[];
      paticon["c"]="<img src='/providerlocator/images/c.jpg' alt=\"This provider offers counseling services for alcohol dependent patients in recovery\" title=\"This provider offers counseling services for alcohol dependent patients in recovery\" border=\"0\"/>";
      paticon["m"]="<img src='/providerlocator/images/m.jpg' alt=\"This provider can prescribe medications and oversee medical therapy for patients in recovery\" title=\"This provider can prescribe medications and oversee medical therapy for patients in recovery\" border=\"0\"/>";
      paticon["i"]="<img src='/providerlocator/images/i.jpg' alt=\"VIVITROL Injection Providers\" title=\"VIVITROL Injection Providers\" border=\"0\"/>";
      paticon["cm"]="<img src='/providerlocator/images/cm.jpg' alt=\"This provider offers counseling and can prescriber medications and oversee medical therapy for patients in recovery\" title=\"This provider offers counseling and can prescriber medications and oversee medical therapy for patients in recovery\" border=\"0\"/>";
      paticon["mi"]="<img src='/providerlocator/images/mi.jpg' alt=\"Provider Offering M and I of the C-M-I Services\" title=\"Provider Offering M and I of the C-M-I Services\" border=\"0\"/>";
      paticon["cmi"]="<img src='/providerlocator/images/cmi.jpg' alt=\"This provider offers counseling and can prescriber medications and oversee medical therapy for patients in recovery\" title=\"This provider offers counseling and can prescriber medications and oversee medical therapy for patients in recovery\" border=\"0\"/>";
      paticon["none"]="";
      //only pat
      var patMap=[];
      patMap["c"] ="c";
      patMap["m"] ="m";
      patMap["i"] ="i";
      patMap["cm"] ="cm";
      patMap["mi"] ="mi";
      patMap["cmi"] ="cmi";
      patMap["none"] ="m"; // default
          
      

      // arrays to hold variants of the info window html with get direction forms open
      var to_htmls = [];
      var from_htmls = [];
      
      
      //Jason Provider count
      var Provider_count = 0;
      //center
      var searchLocation="";
      var zip;
      var city;
      var state;
      var radius = 5;
      var firstname;
      var lastname;
      var zoom_level =15;
//      var section =getURLParam('sec');//either pat or hcp	
	  var section = 'hcp';	//Patient side now same as HCP - GS 12/01/09
      var termsagreed = getURLParam('terms');
      var searchMode = 0 ; //search by geo : 1 : search by first and last name
      var printversion =false;
      var printURL =  "/providerlocator/providerprint.aspx?";
      
  jQuery(function( $ ){

  $("#searchBtn").mouseover(function () {
      $(this).css("background-image","url(images/button_over.jpg)");
    });
  $("#searchBtn").mouseout(function () {
      $(this).css("background-image","url(images/button_on.jpg)");
    });
  if( readCookie('termsagreed')!=null )
   $('input[id=chkTerms]').attr('checked', true);

  $("#map").hide();
  $('#title').hide();
  $('#cmdPrint').hide();
  $("#pager").hide();
  $("#loading").hide();
  $("#toggle_menu").hide();
  $("#legend").hide();
  $("#printMap").hide();

//printable version setting
  var profiles =
    {
      windowCenter:
      {
        height:600,
        width:950,
        center:1 ,
        scrollbars:1
      }
  };
  $(".printWindow").popupwindow(profiles);

	$("input[name='Radius']").change(function(){
	   radius = $(this).val();	 
	   }
  );
	       
  $("#BackToSerach").click(function(){
  
   window.location.reload();
  });

if(getSearchURLParam("zip")||getSearchURLParam("city")||getSearchURLParam("state")||getSearchURLParam("firstname")||getSearchURLParam("lastname")||getSearchURLParam("radius"))
{
    printversion=true;
    $('#map').hide();
    $('#temsandindication').hide();
    zip       = getSearchURLParam("zip");
    city      = getSearchURLParam("city");
    state     = getSearchURLParam("state"); 
    radius     = getSearchURLParam("radius"); 
    
    firstname = getSearchURLParam("firstname");
    lastname  = getSearchURLParam("lastname");
    

    if(zip.length >0 )
    {
      searchLocation = zip;
    }else
    {
      searchLocation=city+ ", "+state;
    }

    if(firstname.length>0 || lastname.length >0 )
    {
      searchMode =1;
    }
    searchtext="";      
    searchtext+=(radius)?radius+" mile area [based on what was selected] ":"";
    searchtext+=(zip.length>0)?zip+" zip code ":"";
    searchtext+=(city.length>0)?city+" city ":"";
    searchtext+=(state.length>0)? state+" state":"";
    searchtext+=(firstname.length>0)?firstname +" firstname":"";
    searchtext+=(lastname.length>0)?lastname+" lastname":"";
    searchtext+="as of "+ Date();        

   

  
    $("#loading").show(); 

     switch(searchMode)
     {
      case 0:
       //alert("Searchby cisty State");
       $.ajax({
          type:"POST",
          url:"/providerlocator/providers.aspx",
          data: {Zip:zip, City:city, Radius:radius, State:state},
          success: function(data){
            if(data.Providers)
               {
                   $("#map").show();
                   $('#temsandindication').show();
                   $("#toggle_menu").show();
                   $('#title').show();
                  // displayMap();
                   init_map();
                   Provider_count =data.Providers.count;
                   loadJson(data,searchLocation);
                   $("#loading").hide();
                   $('#map').show();
                   $('#cmdPrint').show();
                   if(Provider_count ==1)
                     resetMapTo(startPoint);
                    
                    $('#searchDesc').text(searchtext).show(); 
                    $('#searchOrder').text('Providers are listed based on distance');
               }else if(data.errors)
               {
                 alert(data.errors.error);
                 $("#loading").hide();
               }
          
          }, //success
          error:  function(){
            alert("error");
            $("#loading").hide();
          },
          dataType:"json"
        
        });//end of ajax
      break;
    
      case 1:
        //alert("Searchby first");
             $.ajax({
        type:"POST",
        url:"/providerlocator/providers.aspx",
        data: {First:firstname, Last:lastname},
        success: function(data){
          if(data.Providers)
             {
                 $("#map").show();
                 $('#temsandindication').show();
                 //$("#toggle_menu").show();
                // displayMap();

                 init_map();
                 Provider_count =data.Providers.count;
                 loadJson(data,searchLocation);
                 $("#loading").hide();
                 $('#title').show();
                 $('#cmdPrint').show();
                 if(Provider_count ==1)
                   resetMapTo(startPoint);

                if(searchMode==1)
                  {
                   
                    map.setZoom(map.getBoundsZoomLevel(bounds));
                    map.setCenter(bounds.getCenter());                 

                  }
                  $('#searchDesc').text(searchtext).show(); 
                  $('#searchOrder').text('Providers are listed based on ____________ only');
             }else if(data.errors)
             {
               alert(data.errors.error);
               $("#loading").hide();
             }
        
        }, //success
        error:  function(){
          alert("error");
          $("#loading").hide();
        },
        dataType:"json"
      
      });//end of ajax
      break;

     }
}

// serach button event
  $("#searchBtn").click(function(){ 
    /* Code */ 

    zip       = $("#Zip").val();
    city      = $("#City").val();
    state     = $("#State").val(); 
    
    firstname = $("#First").val();
    lastname  = $("#Last").val();
    
    
    //sec=hcp&popupwindow=print&zip=07020
    printURL+="&sec="+section;
    if(zip.length >0 )
    {
      searchLocation = zip;
      printURL+="&zip="+zip;
    }else
    {
      searchLocation=city+ ", "+state;
      printURL+="&city="+city+"&state="+state;
    }

    if(firstname.length>0 || lastname.length >0 )
    {
      searchMode =1;
      printURL+="&firstname="+firstname+"&lastname="+lastname;
    }
    printURL+="&radius="+radius;    
    if($('#chkTerms').attr("checked") == true) // ready to post
    {        
    $("#loading").show(); 
     switch(searchMode)
     {
      case 0:
       //alert("Searchby cisty State");
       $.ajax({
          type:"POST",
          url:"/providerlocator/providers.aspx",
          data: {Zip:zip, City:city, Radius:radius, State:state},
          success: function(data){
            if(data.Providers)
               {
                   $("#map").show();
                   $("#searchForm").hide();
                   $("#toggle_menu").show();
                   $("#printMap").show();
                  // displayMap();
                   init_map();
                   Provider_count =data.Providers.count;
                   loadJson(data,searchLocation);
                   $("#loading").hide();
                   $("#searchForm").hide();
                   if(Provider_count ==1)
                     resetMapTo(startPoint);

                  $('#printMap').attr('href',printURL);
               }else if(data.errors)
               {
                 alert(data.errors.error);
                 $("#loading").hide();
               }
          
          }, //success
          error:  function(){
            alert("error");
            $("#loading").hide();
          },
          dataType:"json"
        
        });//end of ajax
      break;
    
      case 1:
        //alert("Searchby first");
             $.ajax({
        type:"POST",
        url:"/providerlocator/providers.aspx",
        data: {First:firstname, Last:lastname},
        success: function(data){
          if(data.Providers)
             {
                 $("#map").show();
                 $("#searchForm").hide();
                 $("#toggle_menu").show();
                // displayMap();
                 init_map();
                 Provider_count =data.Providers.count;
                 loadJson(data,searchLocation);
                 $("#loading").hide();
                 $("#searchForm").hide();
                 if(Provider_count ==1)
                   resetMapTo(startPoint);

                if(searchMode==1)
                  {
                   
                    map.setZoom(map.getBoundsZoomLevel(bounds));
                    map.setCenter(bounds.getCenter());                 

                  }
                $('#printMap').attr('href',printURL);
             }else if(data.errors)
             {
               alert(data.errors.error);
               $("#loading").hide();
             }
        
        }, //success
        error:  function(){
          alert("error");
          $("#loading").hide();
        },
        dataType:"json"
      
      });//end of ajax
      break;

     }

      //cookie handlder
      if(readCookie('termsagreed')==null)
      {
        createCookie('termsagreed','termsagreed',true);
      }
 
    }else // shoot out message that you need to agree with this
    {
     alert("You must read and agree to the Terms of Use");
    }
    
    return false;
    
   }); // end of .click
    
  //print functionality



  

});// end of onload

//////////////////////////////////////////////////////////////////////////////////////////

			/*
			 * Initializing function.
			 * Creates the GMap2 object used throughout, and sets initial controls and start location
			 */
			 function init()
			 {
			  //dummy init();
			 }
			 
			function init_map() {
				if (GBrowserIsCompatible()) {
					// create the Map object
					map = new GMap2(document.getElementById("map"));
					gdir = new GDirections(map, document.getElementById("directions"));
					map.addControl(new GLargeMapControl());
					map.addControl(new GMapTypeControl());
					map.disableDoubleClickZoom();
					map.enableScrollWheelZoom();
					map.setCenter(startPoint, getZoomLevel(radius));	
					// Create the virtual car marker, add it to the map, and then reset the map
					currentLocation = createCenterMarker(startPoint);
					
					map.addOverlay(currentLocation);
					resetMap();
					
					// === catch Directions errors ===
          GEvent.addListener(gdir, "error", function() {
          var code = gdir.getStatus().code;
          var reason="Code "+code;
          if (reasons[code]) {
            reason = reasons[code]
          } 

          alert("Error: "+reason);
        });
					
				}
			}
			
				/*
			 * Function to reset back to standard content, removing markers, 
			 * setting the polygon radius, fixing up controls, etc.
			 */
			function resetMap()
			{
				// Pan the map back to the original start location
				map.panTo(startPoint, 15);
				// Set the virtual car location back to the start location
				currentLocation.setLatLng(startPoint);
			}
			
		function resetMapTo(point)
		{
		  map.panTo(point, 15);
		  currentLocation.setLatLng(point);
		 
		}
			/*
			 * Function to create the car marker, returning a GMarker object.
			 * @param {GLatLng} latlng - the location object defining where to create the GMarker
			 * @returns GMarker for the virtual car
			 */
			function createCenterMarker(latlng)
			{
				// create a custom "car" icon from an image, setting the size and other attributes
				var func_icon = new GIcon();
				func_icon.image = "images/clear.png";
				func_icon.iconSize = new GSize(40, 40);
				func_icon.shadowSize = new GSize(30, 30);
				func_icon.iconAnchor = new GPoint(20, 20);
				func_icon.infoWindowAnchor = new GPoint(5, 1);
				var func_markerOpts = {};
				func_markerOpts.icon = func_icon;
				// allow the marker to be moved around
				func_markerOpts.draggable = false;
				// create the GMarker object with the specified options
				var func_marker = new GMarker(latlng, func_markerOpts);
				
				return func_marker;
			}
			 
			
  function loadJson(json,loc)
  {
    // Create a new array of GMarkers to contain all of the locations of interest
    markerArray = new Array();
    //reset start point according to the yser serach string
    geocoder.getLocations(loc, function (result)
      { 
       successcode=reasons[result.Status.code] ;
       code =result.Status.code;
      
        if (result.Status.code == G_GEO_SUCCESS) {
 
           p = result.Placemark[0].Point.coordinates;
           lat=p[1];
           lng=p[0];

          startPoint = new GLatLng(lat,lng); 

          if(Provider_count>1 && searchMode ==0)
          map.setCenter(startPoint, getZoomLevel(radius));
           
        }
        // ====== Decode the error status ======
        else 
        {              
          var reason="Code "+result.Status.code;    
          if (reasons[result.Status.code])
            reason = reasons[result.Status.code];                 
        }
      });
      
    
    var dataBody=""; // table data  
    
    if( json.Providers.count == 0 )
    {
     $("#loading").hide();
     alert("There are no Providers matching with your search criteria. Please expand the search radius and try again. ");
     window.location.reload();    
    }
  
    switch(parseInt(json.Providers.count))
    {
      case 0:
       
      break;
      
      case 1:
        var entry = json.Providers.Provider;  
        var address = entry.address1+((entry.address2)?(", "+entry.address2+", "):", ")+entry.city+ ", "+entry.state+ " "+entry.zip;       
        var i=0;
        var type = getProvider(entry.counselor,entry.evaluator,entry.injection ,section);
        var is_c =(entry.counselor =="true")?"<img src='/providerlocator/images/c.jpg' alt=\"Counseling Provider\" title=\"Counseling Provider\" border=\"0\"/>":"";
        var is_m =(entry.evaluator =="true")?"<img src='/providerlocator/images/m.jpg' alt=\"Medical Management Provider\" title=\"Medical Management Provider\" /> ":"";
        var is_i =(entry.injection =="true")?"<img src='/providerlocator/images/i.jpg' alt=\"VIVITROL Injection Provider\" title=\"VIVITROL Injection Provider\" /> ":"";
        var is_r =(entry.referrals =="true")?"<img src='/providerlocator/images/r.jpg' alt=\"VIVITROL Referral Provider\" title=\"VIVITROL Referral Provider\" /> ":"";
       // var func_html ="<div class=\"icontitle\" style=\"text-align:left;\"><img src='/providerlocator/images/vivitrol_small_logo.jpg' /><div class=\"htitle\">Vivitrol Provider Reference #"+(i+1)+"</div>";
        var func_html ="";
        var name =(entry.first_name && entry.last_name)?entry.first_name+ "  "+entry.last_name:"";
        var email =(entry.email)?"<a href=\"mailto:"+entry.email+"\">"+ltrim(entry.email)+"</a>":"";
        var phone = (entry.phone)?entry.phone:"";
        var practice = (entry.practice)?entry.practice:"";     
        var imgicon = ((section == 'pat')? paticon[type] : hcpicon[type]); 
        
        func_html +="<br/>";
        func_html +="<\div>";
        func_html +="<span class=\"centerDetail\">";
        func_html +=(entry.practice)?"<span class=\"title\"><strong>"+practice+"</strong></span><br />":"<span class=\"title\"><strong>Dr. "+name+"</strong></span><br />";
        
        func_html +=address+"<br />";     
        func_html +=((entry.phone)?"&nbsp;"+phone:'')+((entry.email)?"<br/>"+(email):'')+"<br />";    
        func_html +=(entry.first_name)?"<br/><span class=\"title\"><strong>Provider Contact Name:&nbsp;Dr. "+name+"</strong></span><br />":"";                      
        func_html +="<\span><div class=\"label\">";  
        func_html+= (section=="pat")?(paticon[type]+ "&nbsp; "+patlabel[type]):(hcpicon[type]+ "&nbsp; "+hcplabel[type]);
        func_html +="</div>";  
            
        var name =(entry.first_name && entry.last_name)?entry.first_name+ "  "+entry.last_name:"";
        var email =(entry.email)?"<a href=\"mailto:"+entry.email+"\">"+ltrim(entry.email)+"</a>":"";
        var phone = (entry.phone)?entry.phone:"";
        var practice = (entry.practice)?entry.practice:"";      
            
            var row ="<tr>"
                            +"<td>"
                            +"<a href=\"#\" onClick=\"gotoProvider("+i+");\">"+parseInt(i+1)+"</a>"
                            +"</td>"
                            +"<td width=\"80\">"
                            +imgicon
                            +"</td>"
                            +"<td>"
                            +((entry.practice)?practice:((entry.first_name)?name:'')) 
                            +"</td>"
                            +"<td>"
                            +address
                            +"</td>"
                            +"<td>"
                            +name
                            +"</td>"
                            +"<td>"
                            +  ((entry.phone)?"&nbsp;"+phone:'')+((entry.email)?"<br/>"+(email):'')
                            +"</td>"
                            +"</tr>";
       
        var p;
        var lat;
        var lng;
        var successcode;
        var code ;         
       
        var func_point = new GLatLng(parseFloat(entry.lat) ,parseFloat(entry.lon));          
        createProviderMarker(func_point, i , func_html,type);  
        bounds.extend(func_point);          
        dataBody+=row;         
      // Now that the points have been loaded, check to see if any fall within the starting polygon
      //  checkPoints();
      zoom_level =getZoomLevel(radius);
     
      map.setCenter(func_point, 15);
      map.panTo(func_point, 15);
      resetMapTo(func_point);
      startPoint = func_point;
      
      var dataHeader ="<thead><tr><th name=\"distance\">No.</th><th name=\"provider type\">Provider<br/>Type</th>"                                
                                +"<th name=\"provider or facility\">Provider<br/>or Facility</th><th name=\"address\">Address</th><th name=\"provider contact\">Provider Contact</th><th name=\"phone/email\">Phone/Email</th></tr></thead>";
      var data_html = "<table id=\"providerData\" class=\"tablesorter\" border=\"0\" cellpadding=\"0\" cellspacing=\""+((printversion==false)?1:0)+"\">"+dataHeader + "<tbody>"+dataBody+"</tbody>"+"</table>";
      var legend_html = (printversion==false)?((section =="pat")?("<img src=\"/providerlocator/images/legend_pat.jpg\" />"):("<img src=\"/providerlocator/images/legend_hcp.jpg\" />")):"";
      $("#pager").show();
      $("#display").html(data_html);
      (printversion==false)?$("#legend").show():$("#legend").hide();       
      $("#image_lg").html(legend_html);
      (printversion==false)?$("#image_lg").show():$("#image_lg").hide();
      if(printversion==false)
      {
        $("#providerData").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']}).tablesorterPager({container: $("#pager")}); 
      }else
      {
      $("#providerData").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']}); 
      $("#pager").hide();
      }
      
      
      $("#options").tablesorter({sortList: [[0,0]], headers: { 3:{sorter: false}, 4:{sorter: false}}}); 
          
      break;
      
      default:
          for (var i =0; i <json.Providers.Provider.length; i++) 
          {                 
            var entry = json.Providers.Provider[i];  
            var address = entry.address1+((entry.address2)?(", "+entry.address2+", "):", ")+entry.city+ ", "+entry.state+ " "+entry.zip;  
            var type = getProvider(entry.counselor,entry.evaluator,entry.injection ,section);
            var imgicon = ((section == 'pat')? paticon[type] : hcpicon[type]); 
            var is_c =(entry.counselor =="true")?"<img src='/providerlocator/images/c.jpg' alt=\"Counseling Provider\" title=\"Counseling Provider\" border=\"0\"/>":"";
            var is_m =(entry.evaluator =="true")?"<img src='/providerlocator/images/m.jpg' alt=\"Medical Management Provider\" title=\"Medical Management Provider\" /> ":"";
            var is_i =(entry.injection =="true")?"<img src='/providerlocator/images/i.jpg' alt=\"VIVITROL Injection Provider\" title=\"VIVITROL Injection Provider\" /> ":"";
            var is_r =(entry.referrals =="true")?"<img src='/providerlocator/images/r.jpg' alt=\"VIVITROL Referral Provider\" title=\"VIVITROL Referral Provider\" /> ":"";
            //var func_html ="<div class=\"icontitle\" style=\"text-align:left;\"><img src='/providerlocator/images/vivitrol_small_logo.jpg' /><div class=\"htitle\">Vivitrol Provider Reference #"+(i+1)+"</div>";
            var func_html="";           
            var name =(entry.first_name && entry.last_name)?entry.first_name+ "  "+entry.last_name:"";
            var email =(entry.email)?"<a href=\"mailto:"+entry.email+"\">"+ltrim(entry.email)+"</a>":"";
            var phone = (entry.phone)?entry.phone:"";
            var practice = (entry.practice)?entry.practice:"";      
            
            
           
            var row ="<tr>"
                            +"<td>"
                            +"<a href=\"#\" onClick=\"gotoProvider("+i+");\">"+parseInt(i+1)+"</a>"
                            +"</td>"
                            +"<td width=\"80\">"
                            +imgicon
                            +"</td>"
                            +"<td>"
                            +((entry.practice)?practice:((entry.first_name)?name:'')) 
                            +"</td>"
                            +"<td>"
                            +address
                            +"</td>"
                            +"<td>"
                            +name
                            +"</td>"
                            +"<td>"
                            +  ((entry.phone)?"&nbsp;"+phone:'')+((entry.email)?"<br/>"+(email):'')
                            +"</td>"
                            +"</tr>";
            
           
          
            func_html +="<br/>";
            func_html +="<\div>";
            func_html +="<span class=\"centerDetail\">";
            func_html +=(entry.practice)?"<span class=\"title\"><strong>"+practice+"</strong></span><br />":"<span class=\"title\"><strong>Dr. "+name+"</strong></span><br />";
            
            func_html +=address+"<br />";     
            func_html +=((entry.phone)?"&nbsp;"+phone:'')+((entry.email)?"<br/>"+(email):'')+"<br />";    
            func_html +=(entry.first_name)?"<br/><span class=\"title\"><strong>Provider Contact Name:&nbsp;Dr. "+name+"</strong></span><br />":"";                      
            func_html +="<\span><div class=\"label\">";  
            func_html+= (section=="pat")?(paticon[type]+ "&nbsp; "+patlabel[type]):(hcpicon[type]+ "&nbsp; "+hcplabel[type]);
            func_html +="</div>";  
            var p;
            var lat;
            var lng;
            var successcode;
            var code ;
            
            var func_point = new GLatLng(parseFloat(entry.lat) ,parseFloat(entry.lon));          
            createProviderMarker(func_point, i , func_html,type);    
            bounds.extend(func_point);            
            dataBody+=row;   
          }      
          // Now that the points have been loaded, check to see if any fall within the starting polygon
          //  checkPoints();
          zoom_level =getZoomLevel(radius);        
          map.setZoom(zoom_level);
          //resetMap();  
          
           var dataHeader ="<thead><tr><th name=\"distance\">No.</th><th name=\"provider type\">Provider<br/>Type</th>"                                
                                +"<th name=\"provider or facility\">Provider<br/>or Facility</th><th name=\"address\">Address</th><th name=\"provider contact\">Provider Contact</th><th name=\"phone/email\">Phone/Email</th></tr></thead>";
          var data_html = "<table id=\"providerData\" class=\"tablesorter\" border=\"0\" cellpadding=\"0\" cellspacing=\""+((printversion==false)?1:0)+"\">"+dataHeader + "<tbody>"+dataBody+"</tbody>"+"</table>";
          var legend_html =(printversion==false)?( (section =="pat")?("<img src=\"/providerlocator/images/legend_pat.jpg\" />"):("<img src=\"/providerlocator/images/legend_hcp.jpg\" />")):"";
          $("#pager").show();
          $("#display").html(data_html);
          (printversion==false)?$("#legend").show():$("#legend").hide();       
          $("#image_lg").html(legend_html);
          (printversion==false)?$("#image_lg").show():$("#image_lg").hide();
          //$("#providerData").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']}).tablesorterPager({container: $("#pager")}); ;
          if(printversion==false)
          {
            $("#providerData").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']}).tablesorterPager({container: $("#pager")}); 
          }else
          {
            $("#providerData").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']}); 
            $("#pager").hide();
          }
          $("#options").tablesorter({sortList: [[0,0]], headers: { 3:{sorter: false}, 4:{sorter: false}}}); 
      break;           
    }

   

    
  } //end of function
			
			/*
			 * Function that creates a GMarker object for the location of interest, using a custom icon
			 * @param {GLatLng} point - place to create the marker
			 * @param {String} storeNum - HTML string containing a "store number" (i.e. for a retail location)
			 * @param {String} html - HTML string containing descriptive content for the InfoWindow
			 * @returns GMarker for the location
			 */
			function createProviderMarker(point, index, html, type)
			{
        
				var func_icon = new GIcon();
				func_icon.image = "images/"+((section=="pat")?(patMap[type]):type)+".png";
				func_icon.iconSize = new GSize(24, 24);
				func_icon.shadowSize = new GSize(41, 30);
				func_icon.iconAnchor = new GPoint(6, 20);
				func_icon.infoWindowAnchor = new GPoint(5, 1);
				var func_markerOpts = {};
				func_markerOpts.icon = func_icon;
				func_markerOpts.title = "VIVITROL PROVIDER # "+(index+1);
				
				
				  // The info window version with the "to here" form open
				  
        to_htmls[index] = html + '<br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + index + ')">From here<\/a>' +
           '<br>Start address:<form action="javascript:getDirections()">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br/>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT"><br /><br/>' +
           '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + 
           '"/>';
        // The info window version with the "from here" form open
        from_htmls[index] = html + '<br>Directions: <a href="javascript:tohere(' + index + ')">To here<\/a> - <b>From here<\/b>' +
           '<br>End address:<form action="javascript:getDirections()">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br/>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT"><br><br/>' +
           '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
           '"/>';
        // The inactive version of the direction info
        html = "<div class=\"innerbox\">"+html + '<br>Directions: <a href="javascript:tohere('+index+')">To here<\/a> - <a href="javascript:fromhere('+index+')">From here<\/a><br/><br/></div>';
				
			
				
				
				var func_marker = new GMarker(point, func_markerOpts);
				GEvent.addListener(func_marker, "click", function() {
					func_marker.openInfoWindowHtml(html, {maxWidth:400});
				});
				markerArray.push(func_marker);
				map.addOverlay(func_marker); 
       
				return func_marker;
			}
			
			/*
			 *Trigger event
			 */
			 function gotoProvider(n)
			 {
			  GEvent.trigger(markerArray[n], "click");
			 }
			 	
			 
			// functions that open the directions forms
      function tohere(i) {
        markerArray[i].openInfoWindowHtml(to_htmls[i]);
      }
      function fromhere(i) {
        markerArray[i].openInfoWindowHtml(from_htmls[i]);
      } 
			
			function getZoomLevel(r)
			{
			   var z = 10;			   
			   switch(r)
          {
            case 5:
              z =12;
              break;
            
            case 10:
              z = 11;
              break;
            
            case 25:
              z = 10;
              break;
           
           case 50:
              z = 9;
             break;
             
           default:
              z = 10;
              break;   
          }
       
      z=(printversion==true)?z+1:z;
    

       return z;
    }    
    
   
      
	/*
	 *Get direction
	 */
    function getDirections() {
      // ==== Set up the walk and avoid highways options ====
      var opts = {};
     
      // ==== set the start and end locations ====
      var saddr = document.getElementById("saddr").value
      var daddr = document.getElementById("daddr").value
      gdir.load("from: "+saddr+" to: "+daddr, opts);
    }
                  
	// wait for a split second and then initialize the map
	setTimeout('init()', 100) ;
	
	// get url param section
  function getURLParam(strParamName){
    var strReturn = "";
    var strHref = window.location.href;
    if ( strHref.indexOf("?") > -1 ){
      var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
      var aQueryString = strQueryString.split("&");
      for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
        if ( 
  aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
          var aParam = aQueryString[iParam].split("=");
          strReturn = aParam[1];
          break;
        }
      }
    }
    return unescape(strReturn.substr(0,3));
  } 


function getProvider(c, m, i , section)
{
  var str ="none";
  
  if(section =="pat")
  {
    if(c=="true" && m=="true" && i=="true")  str="cmi";    
    if(c=="true" && m== "true" && i!=="true") str="cm";    
    if(c != "true" && i== "true" && m=="true")  str="mi";    
    if(c== "true" && m!="true" && i!="true") str="c";    
    if(c!="true" && i !="true" && m =="true") str="m"    
    if(c!=="true" && i == "true" && m!== "true") str = "i";
        
  }else
  {
    if(c=="true" && m=="true" && i=="true")  str="cmi";    
    if(c=="true" && m== "true" && i!=="true") str="cm";    
    if(c != "true" && i== "true" && m=="true")  str="mi";    
    if(c== "true" && m!="true" && i!="true") str="c";    
    if(c!="true" && i !="true" && m =="true") str="m"    
    if(c!=="true" && i == "true" && m!== "true") str = "i";
  }  

  return str;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function createCookie(name,value,days, expireOnClose) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+(expireOnClose==false)?date.toGMTString():"";
	}
	else var expires = "";
	document.cookie = name+"="+escape(value)+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function getSearchURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if ( 
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
} 