

   var map = null;
    var geocoder = null;
   var http_request = false;
   var baseIcon;
   var geocoder = new GClientGeocoder(); 
       var gto;
    var toggleTraffic = 0;
	var toggleStreet = 0;
    var gdir;
	var svOverlay;
    var addressMarker;
	var marker;
	var markergone = false;
	var icon;
	var overlayInstance = null;
	var client;
	var lastIconLocation;
	var panorama;
	var mapT;
	var defaultLat;
	var defaultLng;
	var currentZoom;
	var IsCamera;
	var isOldIE = false;
	var stepTotal;
	var distvals;
	var lat1;
	var lng1;
	var val1;
	var trafficOptions = {incidents:true};
	var OrigStAddress = "";
	var	OrigCity = "";
	var	OrigZip = "";
	var repeats;
	var	OrigState = "";
	var afflmsg;
   var bounds;
   var gmarkers = []; 
   var geo1 = [];
   var infoaddr1 = [];
   var count1;
   var arrayAddress=new Array();
   var arrayDir=[];
   var resultCnt;
   var PhysID;
   var delay = 100;
   var setSpec = "%";
   var changeSpec = "";
   var addr_distance;
   var zip1;
   var Interval;
   var notfound = false;
   var idvals;
   var locaddr;
   var first;
   var Aliases = new Array();
   var Marker1 = "final_google_icon2.png";
	  	var Marker1_width = 21;
		var Marker1_height = 33;
	  var Marker2 = "BlankMarker3.png";
		var Marker2_width = 20;
		var Marker2_height = 34;
   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]    = "Google was unable to find that location. Try adding more details such as state or zipcode";
     // 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.";
   

	//alert("4705 hamilton dr san francisco, ca 08043".match(/(\w)+,\s[A-Za-z][A-Za-z](\s)+[0-9]{5}(-[0-9]{4})?$/g))
		function loadXMLDoc(dname)
	{
	if (window.XMLHttpRequest)
	  {
	  xhttp=new window.XMLHttpRequest();
	  }
	else
	  {
	  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
	  }
	xhttp.open("GET",dname,false);
	xhttp.send("");
	return xhttp.responseXML;
	} 

function makeRequest(url, id) {
	
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
	  if(id == 1){
	  var tbl = document.getElementById("LocTable");
	  var lastRow = tbl.rows.length;
	  var row = tbl.insertRow(lastRow);
	  row.insertCell(0).innerHTML = "<img src='/images/mozilla_blu.gif' width='16' height='16' alt='Loading...' />"
	  
	  row.setAttribute("id", "Loading");
	  http_request.onreadystatechange = createTable;
	  }
	  else if(id == 2){
	  http_request.onreadystatechange = PhysiciansList;
	  }
	  else if(id == 3){
	  http_request.onreadystatechange = AliasList;
	  }
      http_request.open('GET', url, true);
      http_request.send(null);
	  
	  //return false;
	  
 /*xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

 xmlHttp.open("get", "http://localhost/PracticeMaps/Locations.asmx/GetLocations?zip=19104", true); 

xmlHttp.onreadystatechange=doUpdate; 

xmlHttp.send(); return false; */

} 


   function do_xml(val, lat, lng) {
	val = CheckAlias(val)
	document.Locations.mapaddress.value = val
	setTimeout('get_xml(\'' + val + '\' , \'' + lat + '\', \'' + lng + '\')', 100);
   }
   function get_xml(val, lat, lng) {
	var zip1 = val.match(/([0-9]{5})/g)
	var name = val.match(/^([a-z]+(\'|-|\.\s|\s)?[a-z]*){1,2}$/g)
	var street = val.match(/^(\d{3,})\s?(\w{0,5})\s([a-zA-Z]{2,30})\s([a-zA-Z]{2,15})\.?\s?(\w{0,5})$/g)
	var state = val.match(/\s*(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$/gi)
	var args = getArgs();
   	var spec;
   	var subspec;
	var wcnt = WordCnt(val)
	var range = 10000
	idvals="140,2886,729,3917,2936,480,584,1854,233,3059,2993,455,2371,96,497,3035,190,187,3090,453,3085,3701,3702,3743,1726,3699,3103,3700,11,1706,4037,1669,5693,5699,5729,5732,5802";
		
		
	if(lat != undefined && lat != ""){lat1 = lat}
	if(lng != undefined && lng != ""){lng1 = lng}

			
	   if (args.subspec == undefined)
	   {
	   subspec = "";
	   }
	   else{
	   subspec = args.subspec;
	   }
	   if (args.spec == undefined)
	   {
	   spec = setSpec;
	   }
	   else{
	   spec = args.spec;
	   }
      
	  bounds = new GLatLngBounds();
      
	notfound = false;
	
	if(document.getElementById("xdivmasking"))
	{
  		demomask.hide();
	}
	//alert(" street:"+street+" name:"+name+" state:"+state+" val:"+val+" lat:"+lat+" zip:"+zip1);
	/*if(street == null && name != null && state == null && val != "rerun")
	{
		var mySplitResult = name.toString().replace(".", "").split(" ").reverse();
		if(mySplitResult.length > 2)
		{
		alert("Please enter the first and last name of the provider or a partial last name");
		return false;
		}else if(mySplitResult[1] == undefined)
		{
		mySplitResult[1] = ""	
		}
		
		for(i = 0; i < mySplitResult.length; i++){
			//alert("<br /> Element " + i + " = " + mySplitResult[i]); 
		}
		alert("Please enter a valid city, state, or street address");
		//makeRequest('/PracticeMaps/Locations.asmx/GetProviders?first=' + mySplitResult[1] + '&last=' + mySplitResult[0] + '&spec=' + spec, 1);
	}
	else
	{*/
		if(val == "rerun" && lat != undefined)
		{
			
			showUserAddress(document.Locations.mapaddress.value, "<b>" + document.Locations.mapaddress.value + "</b>" );
			/*if(lat == undefined){lat = ""}
			if(lng == undefined){lng = ""}*/
			//alert('/PracticeMaps/Locations.asmx/GetLocations?zip=asfs&spec=' + spec + '&subspec=' + subspec + '&latitude=' + lat + '&longitude=' + lng + '&idval=' + idvals.replace(/,/g,"-") + '&range=100000&unit=M');
			clearMap()
			 makeRequest('/PracticeMaps/Locations.asmx/GetLocations?zip=&spec=' + spec + '&subspec=' + subspec + '&latitude=' + lat + '&longitude=' + lng + '&idval=' + idvals.replace(/,/g,"-") + '&range='+range+'&unit=M', 1);
		}else{
			
			
				//alert(lat);
				zip1 = ""
				if(lat == undefined || lat == "")
				{
				CheckValue(document.Locations.mapaddress.value)
				return false;
				}else{
				showUserAddress(document.Locations.mapaddress.value, "<b>" + document.Locations.mapaddress.value + "</b>" );
		     
			  if(first == true)
			  {
				range = 9999  
			  }
			   //alert('/PracticeMaps/Locations.asmx/GetLocations?zip=' + zip1 + '&spec=' + spec + '&subspec=' + subspec + '&latitude=' + lat + '&longitude=' + lng + '&idval=' + idvals.replace(/,/g,"-") + '&range='+range+'&unit=M');
			  clearMap()
			  makeRequest('/PracticeMaps/Locations.asmx/GetLocations?zip=' + zip1 + '&spec=' + spec + '&subspec=' + subspec + '&latitude=' + lat + '&longitude=' + lng + '&idval=' + idvals.replace(/,/g,"-") + '&range='+range+'&unit=M', 1);
				
				}

			
		  //setTimeout('MarkersZoom()', 1500);
		//}
	}
   }
   function do_xml2(id, affl) {
   var args = getArgs();
    var subspec;

	   if (args.subspec == undefined)
	   {
	   subspec = "";
	   }
	   else{
	   subspec = args.subspec;
	   }
     	//getArgs("id");
		
      makeRequest('/PracticeMaps/Locations.asmx/Physicians?id=' + id + '&specid=' + subspec + '&affl=' + affl, 2);
	  PhysID = id;
	  //setTimeout('MarkersZoom()', 1500);
	  
   }
   function handleGeoResponse(address)
   {
	   var geocoder = new GClientGeocoder();
	   geocoder.getLocations(address, function (response)
          {   //map.clearOverlays();
			  if (!response || response.Status.code != 200) 
			  {
				alert("Sorry, we were unable to geocode that address");
			  } else {
				var place = response.Placemark[0];
				var point = new GLatLng(place.Point.coordinates[1],
									place.Point.coordinates[0]);
		
				try{ if(OrigStAddress == ""){OrigStAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName}}
				catch(err){ OrigStAddress = ""}
				try{ if(OrigStAddress == ""){OrigStAddress = place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName}}
				catch(err){ OrigStAddress = ""}
				try{ if(OrigStAddress == ""){OrigStAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.AddressLine}}
				catch(err){ OrigStAddress = ""}
				try{ if(OrigCity == ""){OrigCity =	place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;}}
				catch(err){ OrigCity = ""}
				try{ if(OrigCity == ""){OrigCity =	place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName}}
				catch(err){ OrigCity = ""}
				try{ if(OrigZip == ""){OrigZip =	place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber}}				catch(err){ OrigZip = ""}
				try{ if(OrigState == ""){OrigState =	place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName}}
				catch(err){ OrigState = ""}
				
				
			  }
		  });
     } 
	 
function changeList(a, specialty)
{
  setSpec = a;
  if(changeSpec != "")
  {
  findAndReplace('(' + specialty + ')', "Internal Medicine");
  }
  changeSpec = specialty;
  return false;
}
function clearMap()
{
	var Parent = document.getElementById("LocTable");
while(Parent.hasChildNodes())
      {
      Parent.removeChild(Parent.firstChild);
      }
	  map.clearOverlays();
		document.getElementById("directions").innerHTML = ""
		document.getElementById('map-utilities').style.display = 'none';
	//alert(" zip:"+zip1+" name:"+name+" street:"+street+" state:"+state);
	document.getElementById("map-suggestion-box").style.display="none";	
}
function PhysiciansList()
{	

 if (http_request.readyState == 4) {
	 var div = document.getElementById("List" + PhysID);
	
	 if (div)
	 {
	 div.innerHTML = "<img src='/images/mozilla_blu.gif' width='16' height='16' alt='Loading...' />"
	 }
         if (http_request.status == 200) {
			var xmlDoc=http_request.responseXML.documentElement;
			var x = xmlDoc.getElementsByTagName('Physicians');
			if(x.length > 0)
			{
				
				
				var PhysList = "<ul class=\"physician-bubble-list\">";
				
				for (j=x.length-1;j>=0;j--)
					{
							
							/*if(j == x.length-1){
							PhysList = "<li><a href=\"http://pennhealth.com/Wagform/MainPage.aspx?config=provider&P=PP&ID=" + x[j].getElementsByTagName("id")[0].firstChild.nodeValue + "\">" + x[j].getElementsByTagName("name")[0].firstChild.nodeValue + "</a></li>"
							}else{*/
							PhysList = PhysList + "<li><a  target=\"_blank\" href=\"http://pennhealth.com/Wagform/MainPage.aspx?config=provider&P=PP&ID=" + x[j].getElementsByTagName("id")[0].firstChild.nodeValue + "\">" + x[j].getElementsByTagName("name")[0].firstChild.nodeValue + "</a></li>"
							//}
							//if(div){
							div.innerHTML = PhysList;
							//}
							
			
					}	
					div.innerHTML = afflmsg + div.innerHTML + "</ul>";
			}else{
				div.innerHTML = "No Physicians Found";
			}
 		}else{
				div.innerHTML = "No Physicians Found";
		}
	}
	
	
}	
function AliasList()
{	
 if (http_request.readyState == 4) {
	
         if (http_request.status == 200) {
			var xmlDoc=http_request.responseXML.documentElement;
			var x = xmlDoc.getElementsByTagName('PracticeLocations');
			resultCnt = x.length-1
			
			if(resultCnt > -1)
			{
				
				
				for (i=resultCnt; i >=0; i--)    {
				Aliases[i]=new Array(1);
				}
				
				for (j=x.length-1;j>=0;j--)
					{	
					
							Aliases[j][0] = x[j].getElementsByTagName("Alias_Name")[0].firstChild.nodeValue
							Aliases[j][1] = x[j].getElementsByTagName("Replace_Name")[0].firstChild.nodeValue 
							// alert(Aliases[j][1] +" == " + Aliases[j][0]);
					}	
					
			}else{
				 Aliases = [["none","none"]]
			}
 		}else{
				Aliases = [["none","none"]]
		}
	}
	
	
}	
function CheckAlias(a) {
      for (var i=0; i<Aliases.length; i++) {
        if (a.toLowerCase() == Aliases[i][0].toLowerCase())  {a = Aliases[i][1];break;}
      }	  	  
      return a;
    }
function replaceText(str) {
  var replace = new Array("man", "boy");
  var by = new Array("woman", "girl");
  for (var i=0; i<replace.length; i++) {
     str = str.replace(replace[i], by[i]);
  }
  return str;
} 
function place(lat,lng,addr) {
	//alert(lat+" "+lng);
		lat1 = lat;
		lng1 = lng;
		val1 = addr;
        var point = new GLatLng(lat,lng);
		map.setZoom(10); 
        map.setCenter(point,14); 
		
        map.addOverlay(new GMarker(point));
		
		document.Locations.mapaddress.value = addr
        document.getElementById("map-suggestion-box").style.display="none";
		if(document.getElementById("xdivmasking"))
		{
  		demomask.hide();
		}
		do_xml(addr, lat, lng);
      }
     // ===== list of words to be standardized =====
    var standards = [   ["road","rd"],   
                        ["street","st"], 
                        ["avenue","ave"], 
                        ["av","ave"], 
                        ["drive","dr"],
                        ["saint","st"], 
                        ["north","n"],   
                        ["south","s"],    
                        ["east","e"], 
                        ["west","w"],
                        ["expressway","expy"],
                        ["parkway","pkwy"],
                        ["terrace","ter"],
                        ["turnpike","tpke"],
                        ["highway","hwy"],
                        ["lane","ln"]
                     ];
 
    // ===== convert words to standard versions =====
    function standardize(a) {
      for (var i=0; i<standards.length; i++) {
        if (a == standards[i][0])  {a = standards[i][1];}
      }
      return a;
    }
 
    // ===== check if two addresses are sufficiently different =====
    function different(a,b) {
      // only interested in the bit before the first comma in the reply
      var c = b.split(",");
      b = c[0];
      // convert to lower case
      a = a.toLowerCase();
      b = b.toLowerCase();
      // remove apostrophies
      a = a.replace(/'/g ,"");
      b = b.replace(/'/g ,"");
      // replace all other punctuation with spaces
      a = a.replace(/\W/g," ");
      b = b.replace(/\W/g," ");
      // replace all multiple spaces with a single space
      a = a.replace(/\s+/g," ");
      b = b.replace(/\s+/g," ");
      // split into words
      awords = a.split(" ");
      bwords = b.split(" ");
      // perform the comparison
      var reply = false;
      for (var i=0; i<bwords.length; i++) {
        //GLog.write (standardize(awords[i])+"  "+standardize(bwords[i]))
        if (standardize(awords[i]) != standardize(bwords[i])) {reply = true}
      }
      //GLog.write(reply);
      return (reply);
    }
 
 function CheckValue(val) {
        var search = val;
		demomask=new maskpanel();
		document.getElementById("map-suggestion-box").style.display="none";
        // ====== Perform the Geocoding ======        
        geocoder.getLocations(search + ", USA", function (result)
          {
            //map.clearOverlays(); 
			//alert(result.Status.code);
            if (result.Status.code == G_GEO_SUCCESS) {
				OrigStAddress = "";
				OrigCity = "";
				OrigZip = "";
				OrigState = "";
              // ===== If there was more than one result, "ask did you mean" on them all =====
			  //alert(result.Placemark.length)
              if (result.Placemark.length > 1) { 
			  var contentNode = document.getElementById("map-suggestion-box");
			  /*contentNode.id = "box"
			  contentNode.name = "message";
			  contentNode.class = "dialog"*/
               contentNode.innerHTML = "Did you mean:";
                // Loop through the results
				var k = 1
                for (var i=0; i<result.Placemark.length; i++) {
                  var p = result.Placemark[i].Point.coordinates;
				  var place = result.Placemark[i];
                  //contentNode.innerHTML += "<br>"+(i+1)+": <a href='javascript:place(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"<\/a>";
				  //var zipcode = result.Placemark[i].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
				//document.Locations.mapaddress.value = document.Locations.mapaddress.value + " " + zipcode
				//alert(zipcode+" asdfsdf");
				if(place.AddressDetails.Country)
				{
				var State = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName
				if(State == "PA" || State == "NJ" || State == "DE"){
				  contentNode.innerHTML += "<br>"+(k++)+": <a href=\"javascript:place("+p[1]+","+p[0]+",\'" +result.Placemark[i].address.replace(", USA", "")+"\')\">"+ result.Placemark[i].address.replace(", USA", "")+"<\/a>";
				}
				}else{
					
				}
              }
				
				//alert(contentNode.innerHTML);
				if(contentNode.innerHTML != "Did you mean:")
				{
				  demomask.show();
				  document.getElementById("map-suggestion-box").style.display="block";
				}else
				{
				  alert("Please specify city and state to narrow down the results");
				}
				
              }
              // ===== If there was a single marker =====
              else {
				  if (different(search, result.Placemark[0].address)) {
                  document.getElementById("map-suggestion-box").innerHTML = "Did you mean: ";
                  var p = result.Placemark[0].Point.coordinates;
                  document.getElementById("map-suggestion-box").innerHTML += "<br>1: <a href=\"javascript:place("+p[1]+","+p[0]+",\'" +result.Placemark[0].address.replace(", USA", "")+"\')\">"+ result.Placemark[0].address.replace(", USA", "")+"<\/a>";
				  demomask.show();
				  document.getElementById("map-suggestion-box").style.display="block";
                } else {
               // document.getElementById("box").innerHTML = "";
			  // alert(result.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName);
			   //var place = response.Placemark[0];
                var p = result.Placemark[0].Point.coordinates;
				//var zipcode = result.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
				//document.Locations.mapaddress.value = document.Locations.mapaddress.value + " " + zipcode
				//alert(p[1]);
				var place = result.Placemark[0];
				try{ if(OrigStAddress == ""){OrigStAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName}}
				catch(err){ OrigStAddress = ""}
				try{ if(OrigStAddress == ""){OrigStAddress = place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName}}
				catch(err){ OrigStAddress = ""}
				try{ if(OrigStAddress == ""){OrigStAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.AddressLine}}
				catch(err){ OrigStAddress = ""}
				try{ if(OrigCity == ""){OrigCity =	place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;}}
				catch(err){ OrigCity = ""}
				try{ if(OrigCity == ""){OrigCity =	place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName}}
				catch(err){ OrigCity = ""}
				try{ if(OrigZip == ""){OrigZip =	place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber}}				catch(err){ OrigZip = ""}
				try{ if(OrigState == ""){OrigState =	place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName}}
				catch(err){ OrigState = ""}
				
				setTimeout("place("+p[1]+","+p[0]+",'"+result.Placemark[0].address.replace(", USA", "")+"');", 500)
				}
                
              }
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              //alert('Could not find "'+search+ '" ' + reason);
			  alert('Google was unable to find a location called "'+search+ '". Try adding more details to the search such as state or zipcode.');
            }
          }
        );
      }

	

function createTable()
{	

 if (http_request.readyState == 4) {
	
  if(notfound == false)
	{
    if (http_request.status == 200) {
	var xml1 = loadXMLDoc('/heart/patient/locations/defaultlocations.xml');
	var xmlDoc=http_request.responseXML.documentElement;
	var x = xmlDoc.getElementsByTagName('PracticeLocations');
	resultCnt = x.length-1
    //arrayAddr1=new Array(resultCnt);
    arrayAddress = new Array();
		
		 locaddr = document.Locations.mapaddress.value
				
		if(resultCnt > -1)
		{
			 for (i=resultCnt; i >=0; i--)    {
			arrayAddress[i]=new Array(13);
			}
	
			for (j=x.length-1;j>=0;j--)
			{	
				var destaddr2 = ""	
				if(x[j].getElementsByTagName("address1")[0])
				{
					arrayAddress[j][0] = x[j].getElementsByTagName("address1")[0].firstChild.nodeValue
				}else if(x[j].getElementsByTagName("affdisplay")[0] && x[j].getElementsByTagName("zip")[0] == undefined){
					arrayAddress[j][0] = ""
				}else{
					arrayAddress[j][0] = ""
				}
				if(x[j].getElementsByTagName("address2")[0])
				{
					arrayAddress[j][1] = x[j].getElementsByTagName("address2")[0].firstChild.nodeValue
				}else if(x[j].getElementsByTagName("adminappt")[0] && x[j].getElementsByTagName("zip")[0] == undefined){
					arrayAddress[j][1] = ""
				}else{
					arrayAddress[j][1] = ""
				}			
				if(x[j].getElementsByTagName("address3")[0])
				{
					arrayAddress[j][2] = x[j].getElementsByTagName("address3")[0].firstChild.nodeValue
					destaddr2 = destaddr2 + arrayAddress[j][2]
				}else if(x[j].getElementsByTagName("facultyappt")[0] && x[j].getElementsByTagName("zip")[0] == undefined){
					arrayAddress[j][2] = ""
				}else{
					arrayAddress[j][2] = ""
				}
				if(x[j].getElementsByTagName("st")[0])
				{
					arrayAddress[j][3] = x[j].getElementsByTagName("st")[0].firstChild.nodeValue
				}else{
					arrayAddress[j][3] = ""
				}
				if(x[j].getElementsByTagName("city")[0])
				{
					arrayAddress[j][4] = x[j].getElementsByTagName("city")[0].firstChild.nodeValue
				}else{
					arrayAddress[j][4] = ""
				}
				if(x[j].getElementsByTagName("zip")[0])
				{
					arrayAddress[j][5] = x[j].getElementsByTagName("zip")[0].firstChild.nodeValue
				}else{
					arrayAddress[j][5] = ""
				}
				if(x[j].getElementsByTagName("id")[0])
				{
					arrayAddress[j][6] = x[j].getElementsByTagName("id")[0].firstChild.nodeValue
				}else{
					arrayAddress[j][6] = ""
				}
				if(x[j].getElementsByTagName("name")[0])
				{
					arrayAddress[j][7] = x[j].getElementsByTagName("name")[0].firstChild.nodeValue
				}else{
					arrayAddress[j][7] = ""
				}
				if(x[j].getElementsByTagName("specialty")[0])
				{
					arrayAddress[j][8] = x[j].getElementsByTagName("specialty")[0].firstChild.nodeValue
				}else{
					arrayAddress[j][8] = ""
				}
				if(x[j].getElementsByTagName("latitude")[0])
				{

					arrayAddress[j][9] = x[j].getElementsByTagName("latitude")[0].firstChild.nodeValue
				}else{
					arrayAddress[j][9] = ""
				}
				if(x[j].getElementsByTagName("longitude")[0])
				{
					arrayAddress[j][10] = x[j].getElementsByTagName("longitude")[0].firstChild.nodeValue
				}else{
					arrayAddress[j][10] = ""
				}
				/*if(x[j].getElementsByTagName("distance")[0])
				{
					arrayAddress[j][11] = fnLoad("'" + arrayAddress[j][2] + " " + arrayAddress[j][4] + " " + arrayAddress[j][3] + " " + arrayAddress[j][5] + "'","'" + locaddr.replace(/,/g," ") + "'",j );
				}else{*/
					arrayAddress[j][11] = new Array(1)
				/*}*/
				if(x[j].getElementsByTagName("affgroup")[0])
				{
					arrayAddress[j][12] = x[j].getElementsByTagName("affgroup")[0].firstChild.nodeValue
				}else{
					arrayAddress[j][12] = ""
				}
				if(x[j].getElementsByTagName("entitycode")[0])
				{
					arrayAddress[j][13] = x[j].getElementsByTagName("entitycode")[0].firstChild.nodeValue
					//alert(arrayAddress[j][13]);
				}else{
					arrayAddress[j][13] = ""
				}
				destaddr2 = destaddr2 + " " + arrayAddress[j][4] + " " + arrayAddress[j][3] + " " + arrayAddress[j][5] 
				//alert("'" + arrayAddress[j][2] + " " + arrayAddress[j][4] + " " + arrayAddress[j][3] + " " + arrayAddress[j][5] + "','" + locaddr.replace(/,/g," ") + "',"+arrayAddress[j][6] );
				if(first != true)
				{
				fnLoad("'" + arrayAddress[j][2] + " " + arrayAddress[j][4] + " " + arrayAddress[j][3] + " " + arrayAddress[j][5] + "'","'" + locaddr.replace(/,/g," ") + "'",j );	
				}
			}	
			
				//alert(arrayAddress[0][5]);
			/*if(x[0].getElementsByTagName("address3")[0])
			{
				destaddr2 = arrayAddress[0][2] + " " + arrayAddress[0][4] + " " + arrayAddress[0][3] + " " + arrayAddress[0][5] 
			}else{
				destaddr2 = arrayAddress[0][4] + " " + arrayAddress[0][3] + " " + arrayAddress[0][5] 
			}
			fnLoad(destaddr2, document.Locations.mapaddress.value  , 0);
			//pager.showPage(1);*/
			//repeats = 0
			//Interval = setInterval("intervalCheck(" + (x.length-1) + ", '" + locaddr.replace(/,/g," ").replace("Radnor", "Wayne") + "')", 4000);
			

			setTimeout("AddPaging()", 1000);
		}else
		{
			document.getElementById('Loading').innerHTML = "No Results Found"
		}
	
		
	}}else{
			row.insertCell(0).innerHTML = document.Locations.mapaddress.value + "- Not Found"
			row.setAttribute("id", "Loading");
	}
	
	
}


function MarkersZoom()
{
//alert("ffg");
	for (var i=0; i<marker.length; i++) {
		//bounds.extend(marker[i].point);
		}
		//map.setZoom(map.getBoundsZoomLevel(bounds));
		//map.setCenter(bounds.getCenter());
}
	  
function getUserAddress(address, infoaddress, index, name, addr2, id, cnt) {
        geocoder.getLocations(address, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // Lets assume that the first marker is the one we want
			  var p = result.Placemark[0].Point.coordinates;
			  var lat=p[1];
              var lng=p[0];
			  var point = new GLatLng(lat, lng)
			  //alert(point);
              map.setCenter(point, 13);
			  bounds.extend(point);
			  var letter = String.fromCharCode("A".charCodeAt(0) + index);
          	  var letteredIcon = new GIcon(baseIcon);
			  if (addr2 == 'Penn Medicine Radnor' || addr2 == 'Penn Presbyterian Medical Center' || addr2 == 'Pennsylvania Hospital' || addr2 == 'Hospital of the University of Pennsylvania' || addr2 == 'Penn Medicine Radnor' || addr2 == 'Perelman Center for Advanced Medicine' || addr2 == 'Penn Medicine at Rittenhouse' || addr2 == 'Penn Medicine at Bucks County' || addr2 == 'Penn Medicine at Cherry Hill'){
              letteredIcon.image = "pennshield8.png";
			  letteredIcon.iconSize = new GSize(22, 28);
			  }else{
              letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
			  }
              markerOptions = { icon:letteredIcon };
          	  var marker = new GMarker(point, markerOptions);
			  marker.id = index;
              map.addOverlay(marker);
			  //gmarkers.push(marker); 
		map.setZoom(map.getBoundsZoomLevel(bounds));
		map.setCenter(bounds.getCenter());
		//alert(map.getBoundsZoomLevel(bounds));
		 var tabs = [];
            tabs.push(new GInfoWindowTab("Location", infoaddress));
            tabs.push(new GInfoWindowTab("Physicians","<div  style=\"height:150px;width:250px;margin-top:2px;margin-bottom:2px;overflow: auto\" id=\"List" + id + "\">No Physicians Found</div>"));
		  GEvent.addListener(marker, "click", function() {
		 
		 
            marker.openInfoWindowTabsHtml(tabs)
			
		  //marker.openInfoWindowTabsHtml([new GInfoWindowTab(name,"Marker <b>" + letter + "</b>"), new GInfoWindowTab("List of Physicians","Doctor1<br/>Doctor2")]);
            //marker.openInfoWindowHtml("Marker <b>" + letter + "</b>");
          });
		  var args = getArgs(); 
		
		if (args.locid)
		{
			marker.openInfoWindowTabsHtml(tabs)
		}
		   do_xml2(id);
			GEvent.addDomListener(document.getElementById("Loc" + index), 'click', function() {
        GEvent.trigger(marker, 'click');
      });   
            }
            // ====== Decode the error status ======
            else {
              // === if we were sending the requests to fast, try this one again and increase the delay
              if (result.Status.code == G_GEO_TOO_MANY_QUERIES) {
                //nextAddress--;
                delay++;
              } else {
                var reason="Code "+result.Status.code;
                if (reasons[result.Status.code]) {
                  reason = reasons[result.Status.code]
                } 
                alert(address + ' - ERROR = ' +reason);
              }   
            }
            //next();
          }
        );
      }
	  
}	  
function showAddress(address, infoaddress, index, name, addr2, id, dest, orig, cnt) {
//alert(address);
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
				if(cnt == 1){
				//alert(address + " not found 1");
				setTimeout('showAddress('+address+', '+infoaddress+', '+index+', '+name+', '+addr2+', '+id+', '+dest+', '+orig+', 2)', 400);
				}else{
              //alert(address + " not found");
			  }
            } else {
				//oad(dest, orig, j)
				//alert(gdir.getDistance().html);
              //map.setCenter(point, 13);
			  bounds.extend(point);
			  var letter = String.fromCharCode("A".charCodeAt(0) + index);
          	  var letteredIcon = new GIcon(baseIcon);
			  if (addr2 == 'Penn Medicine Radnor' || addr2 == 'Penn Presbyterian Medical Center' || addr2 == 'Pennsylvania Hospital' || addr2 == 'Hospital of the University of Pennsylvania' || addr2 == 'Penn Medicine Radnor' || addr2 == 'Perelman Center for Advanced Medicine' || addr2 == 'Penn Medicine at Rittenhouse' || addr2 == 'Penn Medicine at Bucks County' || addr2 == 'Penn Medicine at Cherry Hill'){
              letteredIcon.image = "http://www.pennmedicine.org/PracticeMaps/Marker/Marker.aspx?text=" + (index+1) + "&img=" + Marker2 + "&width=" + Marker1_width + "&height=" + Marker1_height + "&fontstyle=2&fontcolor=white";
			  letteredIcon.iconSize = new GSize(Marker1_width, Marker1_height);
			  letteredIcon.shadow = "/images/pennmarker_shadow2.png";
			  letteredIcon.shadowSize = new GSize(40, 33);
			  }else{
              letteredIcon.image = "http://www.pennmedicine.org/PracticeMaps/Marker/Marker.aspx?text=" + (index+1) + "&img=" + Marker2 + "&width=" + Marker2_width + "&height=" + Marker2_height +  "&fontstyle=2&fontcolor=white";
			  }
			  var string1 = new String(index);
				if (string1.length > 2)
				{
					letteredIcon.image = letteredIcon.image + "&fontsize=9";
				}
              markerOptions = { icon:letteredIcon };
          	  var marker = new GMarker(point, markerOptions);
			  marker.id = index;
              map.addOverlay(marker);
			  //gmarkers.push(marker); 
		map.setZoom(map.getBoundsZoomLevel(bounds));
		map.setCenter(bounds.getCenter());
		//alert(map.getBoundsZoomLevel(bounds));
		  GEvent.addListener(marker, "click", function() {
		  
		  var tabs = [];
		  
            tabs.push(new GInfoWindowTab("Location", "<div class=\"LocationBubble\" style=\"height:150px;width:250px;margin-top:2px;margin-bottom:2px;overflow: auto\" id=\"Info" + id + "\">" + infoaddress + "</div>"));
            tabs.push(new GInfoWindowTab("Physicians","<div class=\"PhysicianBubble\" style=\"height:150px;width:250px;margin-top:2px;margin-bottom:2px;overflow: auto\" id=\"List" + id + "\"><img src='/images/mozilla_blu.gif' width='16' height='16' alt='Loading...' /></div>"));
            marker.openInfoWindowTabsHtml(tabs)
			var affl
			switch(id)
			{
			case 729:
			  affl = "PAH"
			  afflmsg = "<p class=\"physician-bubble-title\">The following providers are affiliated with this location.</p>"
			  break;
			case 2886:
			  affl = "PMC"
			  afflmsg = "<p class=\"physician-bubble-title\">The following providers are affiliated with this location.</p>"
			  break;
			case 140:
			  affl = "HUP"
			  afflmsg = "<p class=\"physician-bubble-title\">The following providers are affiliated with this location.</p>"
			  break;
			case 3917:
			  affl = "CAM"
			  afflmsg = "<p class=\"physician-bubble-title\">The following providers are affiliated with this location.</p>"
			  break;
			default:
			  affl = null
			  afflmsg = ""
			}
			var Checktab = setTimeout ("do_xml2(" + id + ", '" + affl + "')", 500);
			Checktab = ""
			//do_xml2(id);
		  //marker.openInfoWindowTabsHtml([new GInfoWindowTab(name,"Marker <b>" + letter + "</b>"), new GInfoWindowTab("List of Physicians","Doctor1<br/>Doctor2")]);
            //marker.openInfoWindowHtml("Marker <b>" + letter + "</b>");
          });
		  var args = getArgs(); 
		
		if (args.locid)
		{
			GEvent.trigger(marker, 'click');
		}
			GEvent.addDomListener(document.getElementById("Loc" + id + index), 'click', function() {
        GEvent.trigger(marker, 'click');
      });   
            }
          }
        );		
      }
    }
	
	
	function showUserAddress(address, infoaddress) {
		//alert(address+"  -  "+infoaddress);
      if (geocoder) {
        geocoder.getLocations(
          address,
          function(response) {
            if (response && response.Status.code == 200) {
              //alert(address + " noot found");
			   var place = response.Placemark[0];
				var point = new GLatLng(place.Point.coordinates[1],
									place.Point.coordinates[0]);
		
				try{ if(OrigStAddress == ""){OrigStAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName}}
				catch(err){ OrigStAddress = ""}
				try{ if(OrigStAddress == ""){OrigStAddress = place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName}}
				catch(err){ OrigStAddress = ""}
				try{ if(OrigStAddress == ""){OrigStAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.AddressLine}}
				catch(err){ OrigStAddress = ""}
				try{ if(OrigCity == ""){OrigCity =	place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;}}
				catch(err){ OrigCity = ""}
				try{ if(OrigCity == ""){OrigCity =	place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName}}
				catch(err){ OrigCity = ""}
				try{ if(OrigZip == ""){OrigZip =	place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber}}				catch(err){ OrigZip = ""}
				try{ if(OrigState == ""){OrigState =	place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName}}
				catch(err){ OrigState = ""}
				if(OrigStAddress == undefined){OrigStAddress = ""}
				if(OrigCity == undefined){OrigCity = ""}
				if(OrigZip == undefined){OrigZip = ""}
				if(OrigState == undefined){OrigState = ""}
				
			  bounds.extend(point);
			 
			 // var letter = String.fromCharCode("A".charCodeAt(0) + index);
          	  var letteredIcon = new GIcon(baseIcon);
              letteredIcon.image = "/images/you-are-here_btn-1.png";
			  letteredIcon.iconSize = new GSize(30, 30);
			  letteredIcon.shadow = "/images/you-are-here_btn-1_shadow.png";
			  letteredIcon.shadowSize = new GSize(50, 30);
			  letteredIcon.transparent = "/images/you-are-here_btn-1_transparent.png";
			  letteredIcon.imageMap = [27,0,30,1,32,2,33,3,34,4,35,5,36,6,37,7,37,8,38,9,38,10,39,11,39,12,39,13,39,14,39,15,39,16,39,17,39,18,39,19,39,20,39,21,39,22,39,23,39,24,39,25,39,26,39,27,39,28,39,29,39,30,39,31,38,32,38,33,37,34,36,35,35,36,35,37,33,38,32,39,5,39,4,38,3,37,2,36,1,35,0,34,0,33,0,32,0,31,0,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,1,7,1,6,2,5,3,4,4,3,6,2,8,1,10,0];
              markerOptions = { icon:letteredIcon };
          	  var marker = new GMarker(point, markerOptions);
              map.addOverlay(marker);
			  //gmarkers.push(marker); 
		map.setZoom(map.getBoundsZoomLevel(bounds));
		map.setCenter(bounds.getCenter());
		//alert(map.getBoundsZoomLevel(bounds));
		  GEvent.addListener(marker, "click", function() {
		  
		  //marker.openInfoWindowTabsHtml([new GInfoWindowTab(name,"Marker <b>" + letter + "</b>"), new GInfoWindowTab("List of Physicians","Doctor1<br/>Doctor2")]);
            marker.openInfoWindowHtml("<br/>" + infoaddress);
          });

            } else {
				notfound = true;
			  
			  
            }
          }
        );		
      }
    }
	
	
	google.load("maps", "2.x");
	
	google.setOnLoadCallback(function() {
									  document.getElementById("map-application").innerHTML = '<p class="intro" id="map-form-intro">Penn Heart and Vascular providers are available to see patients at hospitals and outpatient offices throughout the Greater Philadelphia region. Please use the interactive map below for more information and driving directions to a location near you.</p><form action=\"\" name=\"Locations\" id=\"map-form\" method=\"get\" onsubmit=\"do_xml(this.mapaddress.value, \'\', \'\');first=false; return false\"><fieldset id=\"map-search-location\"><p class=\"mapaddress-instructions\">Please enter your address (including city and state) or zip code.</p><input type=\"text\" id=\"mapaddress\" name=\"mapaddress\" value=\"Please enter your address (including city and state) or zip code\" /><input type=\"image\" src=\"/images/shared/map/enter_btn.gif\" id=\"map-submit\" name=\"map-submit\" value=\"Search\" /></fieldset><div id=\"map-form-results\"><div id=\"printReady\"><div id=\"practice-map-list\"></div><div id=\"practice-map\" ><p>Map is loading...</p></div><div id=\"map-suggestion-box\"> </div></div><div id=\"map-utilities\"></div><div id=\"directions\"></div></div> </form>';
		/*if (google.loader.ClientLocation) {
			var cl = google.loader.ClientLocation;
			var location = [cl.address.city, cl.address.region, cl.address.country].join(', ');
			

			initialize(cl.latitude, cl.longitude, location);
		} else {*/
			initialize(39.948174225938324, -75.1907730102539, "Philadelphia, PA, USA");
		//}
	});
	
    function initialize(lat, lng, location) {
		document.Locations.mapaddress.value = location
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
			 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
			 if (ieversion<=6)
			 isOldIE = true;
			}
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("practice-map"));
		gdir = new GDirections(map);
		gto = new GTrafficOverlay(trafficOptions); 
		svOverlay = new GStreetviewOverlay();
		geocoder = new GClientGeocoder();
		client = new GStreetviewClient();
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new TextualHybridControl());
		//map.setCenter(new GLatLng(0,0),0);
        map.setCenter(new GLatLng(lat, lng), 13);
        geocoder = new GClientGeocoder();
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
	         // ========== launch the custom Panel creator a millisecond after the GDirections finishes loading ==========
      // == The delay is required in case we rely on GDirections to perform the initial setCenter ==
      GEvent.addListener(gdir,"load", function() {

        setTimeout('customPanel(map,"map",gdir,document.getElementById("directions"))', 1);
      });

        GEvent.addListener(gdir, "error", handleErrors);
		GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay);
		
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		var maplist = document.getElementById("practice-map-list");
		maplist.innerHTML = "<table border='0' id='LocTable' ></table>";
		idvals="140,3917,2886,3742";
		//alert(idvals);
		/*if(document.getElementById("map-search-location").style.display == "none")
		{*/
		makeRequest('/PracticeMaps/Locations.asmx/MapAlias', 3);
			bounds = new GLatLngBounds();
		var args = getArgs(); 
		
		if (args.locid)
		{
		  var idfind = args.locid;
		  makeRequest('/PracticeMaps/Locations.asmx/GetLocations?zip=&spec=%&subspec=&latitude=&longitude=&idval=' + idfind.replace(/,/g,"-") + '&range=10000&unit=M', 1);
		}else{
			if(location != "")
			{	
				first = true
				do_xml(location, lat, lng)
			}
		//makeRequest('/heart/patient/locations/defaultlocations.xml', 1);
		}
		//}
      }
    }
	
	
	function deleteRows() 
{ 
    var table = document.getElementById('LocTable'); 
    var rows = table.rows; 
    while(rows.length) // length=0 -> stop 
        table.deleteRow(rows.length-1); 
} 
	function RemoveRow(index)
{
        var parent = document.getElementById(index).parentNode;
        parent.removeChild(document.getElementById(index));
}
	  
	  String.prototype.replaceAll = function( 
		strTarget, // The substring you want to replace
		strSubString // The string you want to replace in.
		){
		var strText = this;
		var intIndexOfMatch = strText.indexOf( strTarget );
		 
		
		// Keep looping while an instance of the target string
		// still exists in the string.
		while (intIndexOfMatch != -1){
		// Relace out the current instance.
		strText = strText.replace( strTarget, strSubString )
		 
		
		// Get the index of any next matching substring.
		intIndexOfMatch = strText.indexOf( strTarget );
		}
		 
		
		// Return the updated string with ALL the target strings
		// replaced out with the new substring.
		return( strText );
		}
		
		
	function getArgs(param) { 
		var args = new Object(); 
		var query = location.search.substring(1); 
		var pairs = query.split("&"); 
		for(var i = 0; i < pairs.length; i++) 
		{ 
			var pos = pairs[i].indexOf('='); 
			if (pos == -1) continue; 
			var argname = pairs[i].substring(0,pos); 
			var value = pairs[i].substring(pos+1); 
			value = value.replaceAll("+", " ")
			args[argname] = unescape(value); 
		} 
			return args; 
		} 
		
	function Pager(tableName, itemsPerPage) {
    this.tableName = tableName;
    this.itemsPerPage = itemsPerPage;
    this.currentPage = 1;
    this.pages = 0;
    this.inited = false;
    
    this.showRecords = function(from, to) {        
        var rows = document.getElementById(tableName).rows;
        // i starts from 1 to skip table header row
        for (var i = 0; i < rows.length; i++) {
			
            if (i < from || i > to)  {
			//alert(i+" <"+from+" and >"+to);
                rows[i].style.display = 'none';
			}else{
                rows[i].style.display = '';
			}
        }
    }
	
	 this.ReloadList = function(num) {  
	 deleteRows(); 
	 if(first != true)
	 {
	 arrayAddress.sort(mySorting);
	 }
	 /*if(document.getElementById('Loading'))
	 {
	 RemoveRow('Loading');
	 }else{
	 RemoveRow('Row2886');
	 }*/
	 //map.clearOverlays(); 
	var tbl = document.getElementById("LocTable");
	var lastRow = tbl.rows.length;
	
	//if(OrigState != undefined  && OrigCity != undefined){
	var origaddr = "&origaddress=" + escape(OrigStAddress) + "&origcity=" + escape(OrigCity) + "&origstateProvince=" + escape(OrigState) + "&origpostalCode=" + escape(OrigZip);
	//}
	//alert(origaddr);
	
	
	
		//document.getElementById("heading").innerHTML = arraySpec[resultCnt] 
		
		//findAndReplace('(internal medicine|Internal Medicine)', arraySpec[resultCnt]);
		
		for (j=num;j>num-10;j--)
		{
			if(arrayAddress[j])
			{
			var imgsrc = "http://www.pennmedicine.org/PracticeMaps/Marker/Marker.aspx?text=" + (j+1) + "&img=" + Marker2 + "&width=" + Marker2_width + "&height=" + Marker2_height +  "&fontstyle=2&fontcolor=white";
			//alert("/PracticeMaps/Marker/Marker.aspx?text=" + (j+1) + "&img=" + Marker2 + "&width=" + Marker2_width + "&height=" + Marker2_height +  "&fontstyle=2&fontcolor=white");
			//var imgsrc = "http://www.google.com/mapfiles/marker" + String.fromCharCode('A'.charCodeAt(0) + j) + ".png"
			if(arrayAddress[j])
				{
					if (arrayAddress[j][0].replace("'", "&#39;") == 'Penn Medicine Radnor' || arrayAddress[j][0].replace("'", "&#39;") == 'Penn Presbyterian Medical Center' || arrayAddress[j][0].replace("'", "&#39;") == 'Pennsylvania Hospital' || arrayAddress[j][0].replace("'", "&#39;") == 'Hospital of the University of Pennsylvania' || arrayAddress[j][0].replace("'", "&#39;") == 'Penn Medicine Radnor' || arrayAddress[j][0].replace("'", "&#39;") == 'Perelman Center for Advanced Medicine' || arrayAddress[j][0].replace("'", "&#39;") == 'Penn Medicine at Rittenhouse' || arrayAddress[j][0].replace("'", "&#39;") == 'Penn Medicine at Bucks County' || arrayAddress[j][0].replace("'", "&#39;") == 'Penn Medicine at Cherry Hill')
					{
						imgsrc = "http://www.pennmedicine.org/PracticeMaps/Marker/Marker.aspx?text=" + (j+1) + "&img=" + Marker2 + "&width=" + Marker1_width + "&height=" + Marker1_height +  "&fontstyle=2&fontcolor=white";
						//imgsrc = "pennshield.png"
					}
				}
			
					var string1 = new String(j);
					if (string1.length > 2)
					{
						imgsrc = imgsrc + "&fontsize=9";
					}
					
					var tag = ""
					/*if(arrayAddress[j][12].indexOf("Clinical Health Care Associates") > -1)
					{
						tag = "+"
					}
					else*/ if(arrayAddress[j][12].indexOf("Independent") > -1)
					{
						tag = "&#9674;"
					}
					if(arrayAddress[j][12].indexOf("Clinical Care Associates") > -1)
					{
						//tag = "*"
					}
					if(arrayAddress[j][13])
					{
						//tag = "&#0135;"
					}
					//alert(arrayAddress[j][12] + " - " + arrayAddress[j][7]);
					
				var row = tbl.insertRow(lastRow);
				row.setAttribute("id", "Row"+arrayAddress[j][6]);
				var cellHTML = "<img src='" + imgsrc + "' ></td><td ><font style='text-decoration:underline;font-weight:bold'>" + arrayAddress[j][7] + "</font>"+ tag +"<br/>" 
				var geo = ""
				var addr2_exists = ""
				var destaddr = "&destpracname=" + escape(arrayAddress[j][7]) 
				var destaddr2 = ""
				var infoaddr = "<b>" + arrayAddress[j][7] + tag + "</b><br/>"
				infoaddr = infoaddr.replace("'", "&#39;")
				if(arrayAddress[j][0])
				{
				//cellHTML = cellHTML + arrayAddress[j][0] + "<br/>"
				//geo = geo + arrayAddr1[j] + " "
				//infoaddr = infoaddr + arrayAddress[j][0] + "<br/>"
				addr2_exists = arrayAddress[j][0]
				}
				if(arrayAddress[j][1])
				{
				cellHTML = cellHTML + arrayAddress[j][1] + "<br/>" 
				//geo = geo + arrayAddress[j][1] + " "
				//infoaddr = infoaddr + arrayAddress[j][1] + "<br/>"
				}
				if(arrayAddress[j][2])
				{
				cellHTML = cellHTML + arrayAddress[j][2] + "<br/>"
				geo = geo + arrayAddress[j][2] + " " 
				infoaddr = infoaddr + arrayAddress[j][2] + "<br/>" 
				destaddr = destaddr + "&destaddress=" + escape(arrayAddress[j][2]) 
				destaddr2 = destaddr2 + arrayAddress[j][2]
				}
				if(arrayAddress[j][3])
				{
				cellHTML = cellHTML + arrayAddress[j][4] + ", " + arrayAddress[j][3] + "  " + arrayAddress[j][5] + "<br/>" 
				if(arrayAddress[j][13])
				{
				cellHTML = cellHTML + "<font style='font-size:7pt;font-weight:bold'>A facility of the Hospital of the University of Pennsylvania</font>" + "<br/>"
				}

				geo = geo +  arrayAddress[j][4] + ", " + arrayAddress[j][3] + "  " + arrayAddress[j][5]
				infoaddr = infoaddr +  arrayAddress[j][4] + ", " + arrayAddress[j][3] + "  " + arrayAddress[j][5] + "<br/>" 
				
				destaddr = destaddr + "&destcity=" + escape(arrayAddress[j][4]) + "&deststateProvince=" + escape(arrayAddress[j][3]) + "&destpostalCode=" + escape(arrayAddress[j][5]) 
				destaddr2 = destaddr2 + " " + arrayAddress[j][4] + " " + arrayAddress[j][3] + " " + arrayAddress[j][5] 
				}
				if(arrayAddress[j][11][1] != undefined && arrayAddress[j][11][0] != undefined)
				{
					var dist = arrayAddress[j][11][1]
				}else{
					var dist = "&nbsp;"	
				}
				var args = getArgs(); 
				if (first == true)
				{
					arrayAddress[j][11][0] = ""
					dist = "&nbsp;"	
					
				}
				row.insertCell(0).innerHTML = "<table style='cursor:pointer' border='0' cellspacing='0' cellpadding='0' id='Loc" + arrayAddress[j][6] + j + "' ><tr><td valign='top' border>" + cellHTML + "</td></tr></table><div style='padding-left:20px' id=\"Dir" + arrayAddress[j][6] + "\" class=\"map-distance\" >" +  dist +"</div><input name=\"ID" +  arrayAddress[j][6] + "\" type=\"hidden\" value=\"" + arrayAddress[j][6] + "\" />"
				
				//if(OrigState != undefined  && OrigCity != undefined){
				infoaddr = infoaddr +  "<a href=\"http://pennhealth.com/gmaps.html?tempset=route&transaction=route" + destaddr + origaddr + "\" target=\"_blank\">Directions</a><br/><br/>"
				
				if(arrayAddress[j][13])
				{
				infoaddr = infoaddr + "<font style=\"font-size:7pt;font-weight:bold\">A facility of the Hospital of the University of Pennsylvania</font><br/>"
				}
				/*}else
				{
					infoaddr = infoaddr +  "<a href=\"http://pennhealth.com/gmaps.html?tempset=route&transaction=route" + destaddr + "\" target=\"_blank\">Directions</a>"
				}*/
				//alert(arrayAddress[j][11]);
				if(first == true && j > 3)
				{
				fnLoad(destaddr2, locaddr,arrayAddress[j][6]);
				}
				setTimeout('showAddress(\'' + geo.replace("'", "&#39;") + '\', \'' + infoaddr.replace("'", "&#39;") + '\', ' + j + ', \'' + arrayAddress[j][7].replace("'", "&#39;") + '\', \'' + addr2_exists.replace("'", "&#39;") + '\', ' + arrayAddress[j][6] + ', \'' + destaddr2 + '\', \'' + locaddr + '\');', delay);
				}
		}
	
	//first = false
    }
    
    this.showPage = function(pageNumber) {
    	if (! this.inited) {
    		alert("not inited");
    		return;
    	}

        var oldPageAnchor = document.getElementById('pg'+this.currentPage+"1");
        //var oldPageAnchor2 = document.getElementById('pg'+this.currentPage+"2");
        oldPageAnchor.className = 'page';
        //oldPageAnchor2.className = 'pg-normal';

		this.currentPage = pageNumber;
        var newPageAnchor = document.getElementById('pg'+this.currentPage+"1");
        //var newPageAnchor2 = document.getElementById('pg'+this.currentPage+"2");
        newPageAnchor.className = 'selected';
        //newPageAnchor2.className = 'pg-selected';
		
        
        var from = (pageNumber - 1) * itemsPerPage ;
        var to = from + itemsPerPage - 1;
		//pager.showPageNav('pager', 'map-utilities', pageNumber); 
        //this.showRecords(from, to);
		this.ReloadList((10*pageNumber)-1)
		
		var pgNext1 = document.getElementById('pgNext1');
		var pgPrev1 = document.getElementById('pgPrev1');
		//var pgNext2 = document.getElementById('pgNext2');
		//var pgPrev2 = document.getElementById('pgPrev2');
		for (var page=1; page <= this.pages; page++)  
		{
			if(pageNumber < 3 && page == 1)
			{
				pageNumber = 3
			}
			else if (pageNumber > this.pages-3 && page == 1)
			{
				pageNumber = this.pages-3
			}
			var pagelist = document.getElementById('pg'+page+'1')
			
			//alert("page="+pageNumber+"; "+page+" <= "+this.pages+"; "+page+"++");
			//alert(pageNumber);
		
				if(page >= (pageNumber+3) || page <= (pageNumber-3))
				{
					pagelist.style.display = "none"
					pagelist.innerHTML = "";
				}
				else
				{
					pagelist.style.display = "inline"
					pagelist.innerHTML = page;
				}
		
		}
		if (resultCnt <= 10)
		{
		document.getElementById('map-utilities').style.display = 'none';
		//document.getElementById('pageNavPosition2').style.display = 'none';
		}else{
		document.getElementById('map-utilities').style.display = 'block';
		//document.getElementById('pageNavPosition2').style.display = 'block';
		}
		if (pageNumber == this.pages)
		{
		pgNext1.style.display = 'none';
		//pgNext2.style.display = 'none';
		}else{
		pgNext1.style.display = 'inline';
		//pgNext2.style.display = 'block';
		}
		if (pageNumber == 1)
		{
		pgPrev1.style.display = 'none';
		//pgPrev2.style.display = 'none';
		}else{
		pgPrev1.style.display = 'inline';  
		//pgPrev2.style.display = 'block';  
		}   
	}   
    
    this.prev = function() {
        if (this.currentPage > 1)
            this.showPage(this.currentPage - 1);
    }
    
    this.next = function() {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);
        }
    }                        
    
    this.init = function() {		
        var rows = document.getElementById(tableName).rows;
        var records = resultCnt /*(rows.length - 1); */
        this.pages = Math.ceil(records / itemsPerPage);
        this.inited = true;
    }

    this.showPageNav = function(pagerName, positionId, cnt, id) {
		clearMap()
		showUserAddress(document.Locations.mapaddress.value, "<b>" + document.Locations.mapaddress.value + "</b>" );
    	if (! this.inited) {
    		alert("not inited");
    		return;
    	}
    	var element = document.getElementById(positionId);
		//alert(positionId);
    	//if(this.pages > 1){
		var pageNumber = cnt
		if(pageNumber < 3)
			{
				pageNumber = 3
			}
			else if (pageNumber > this.pages-2)
			{
				pageNumber = this.pages-2
			}
    	var pagerHtml = '<p id="map-pager" ><a class="prev"  onclick="pager.showPageNav(\'pager\', \'map-utilities\',' + (cnt-1) + ', \'pg'+ (cnt-1) +'1\');return false;" id="pgPrev1">prev</a>';
		pagerHtml += '&nbsp;<a id="pg11"  class="page" onclick="pager.showPageNav(\'pager\', \'map-utilities\',1,\'pg11\');return false;">1</a>';
		
        for (var page = 2; page <= this.pages-1; page++)  
		{
			if(page >= (pageNumber+3) || page <= (pageNumber-3))
				{
					
				}
				else
				{
					pagerHtml += '&nbsp;<a id="pg' + page +'1"  class="page" onclick="pager.showPageNav(\'pager\', \'map-utilities\',' + page + ', \'pg' + page + '1\');return false;">' + page + '</a>';
				}
		}
		pagerHtml += '&nbsp;<a id="pg' + this.pages + '1" class="page" onclick="pager.showPageNav(\'pager\', \'map-utilities\',' + this.pages + ', \'pg' + this.pages + '1\');return false;">' + this.pages + '</a>';
        pagerHtml += '<a onclick="pager.showPageNav(\'pager\', \'map-utilities\',' + (cnt+1) + ', \'pg'+ (cnt+1) +'1\');return false;" class="next" id="pgNext1">next</a></p>';            
        
		
        element.innerHTML = pagerHtml + "<p id=\"view-lg-map\"></p>";
		
		if(cnt > 4)
		{
				document.getElementById("pg11").innerHTML = "1..."
		}
		if(cnt < this.pages-3)
		{
				document.getElementById("pg" + this.pages  + "1").innerHTML = "..." + this.pages		
		}
		
		if(id == "none")
		{
			 var oldPageAnchor = document.getElementById("pg11");
			//var oldPageAnchor2 = document.getElementById('pg'+this.currentPage+"2");
			oldPageAnchor.className = 'page';
			//oldPageAnchor2.className = 'pg-normal';
			this.currentPage = "pg11";
		}else{
			if(document.getElementById(this.currentPage))
			{
			var oldPageAnchor = document.getElementById(this.currentPage);
			//var oldPageAnchor2 = document.getElementById('pg'+this.currentPage+"2");
			oldPageAnchor.className = 'page';
			//oldPageAnchor2.className = 'pg-normal';
			}
			this.currentPage = id;
		}
        var newPageAnchor = document.getElementById(this.currentPage);
        //var newPageAnchor2 = document.getElementById('pg'+this.currentPage+"2");
        newPageAnchor.className = 'selected';
        //newPageAnchor2.className = 'pg-selected';
		
        
        var from = (cnt - 1) * itemsPerPage ;
        var to = from + itemsPerPage - 1;
		//pager.showPageNav('pager', 'map-utilities', pageNumber); 
        //this.showRecords(from, to);
		//alert((10*cnt)-1);
		this.ReloadList((10*cnt)-1)
		
		var pgNext1 = document.getElementById('pgNext1');
		var pgPrev1 = document.getElementById('pgPrev1');
		//var pgNext2 = document.getElementById('pgNext2');
		//var pgPrev2 = document.getElementById('pgPrev2');
		/*for (var page=1; page <= this.pages; page++)  
		{
			if(pageNumber < 3 && page == 1)
			{
				pageNumber = 3
			}
			else if (pageNumber > this.pages-3 && page == 1)
			{
				pageNumber = this.pages-3
			}
			var pagelist = document.getElementById('pg'+page+'1')
			
			//alert("page="+pageNumber+"; "+page+" <= "+this.pages+"; "+page+"++");
			//alert(pageNumber);
		
				if(page >= (pageNumber+3) || page <= (pageNumber-3))
				{
					pagelist.style.display = "none"
					pagelist.innerHTML = "";
				}
				else
				{
					pagelist.style.display = "inline"
					pagelist.innerHTML = page;
				}
		
		}*/
		if (resultCnt <= 10)
		{
		document.getElementById('map-utilities').style.display = 'none';
		//document.getElementById('pageNavPosition2').style.display = 'none';
		}else{
		document.getElementById('map-utilities').style.display = 'block';
		//document.getElementById('pageNavPosition2').style.display = 'block';
		}
		if (cnt == this.pages)
		{
		pgNext1.style.display = 'none';
		//pgNext2.style.display = 'none';
		}else{
		pgNext1.style.display = 'inline';
		//pgNext2.style.display = 'block';
		}
		if (cnt == 1)
		{
		pgPrev1.style.display = 'none';
		//pgPrev2.style.display = 'none';
		}else{
		pgPrev1.style.display = 'inline';  
		//pgPrev2.style.display = 'block';  
		}   
		
		//}
    }
}

 function fnLoad(to, from, j){
	 //alert(to+" - "+from+" / " +j);
	 
                 var dirn = new GDirections();
  
		/*geocoder.getLatLng(to, function(point)
				   {
					   if(!point)
					   {
				   			fnLoad(to , from  , j );
					   }else{
						   arrayPoint[j] = new GLatLng(point.lat(), point.lng());*/
						   //fnLoad(arrayPoint[j] , orig  , id );
						   GEvent.addListener(dirn,"error", function() {
                        //GLog.write(j + " Failed: from: " + from + " to: " + to);
							if(first != true)
								{
							arrayAddress[j][11][0] =   parseFloat(0.0)
								}
						  });
		

						  GEvent.addListener(dirn,"load", function() {
											   
								//GLog.write("The distance for " + j + " is "+dirn.getDistance().html);
								if(first == true)
								{
								var curlink = document.getElementById('Dir'+j);
								curlink.innerHTML = dirn.getDistance().html.replace("mi", "miles").replace("ft", "feet")
								}
								else
								{
									
								var curlink = dirn.getDistance().html.replace(",", "").replace("mi", "").replace("ft", "")
								arrayAddress[j][11][1] =   dirn.getDistance().html.replace("mi", "miles").replace("ft", "feet")
								if(dirn.getDistance().html.indexOf("ft") != -1)
									{
										arrayAddress[j][11][0] =   parseFloat(curlink) / 5280
									}else
									{
										arrayAddress[j][11][0] =   parseFloat(curlink) 
									}
								
								
								}
								/*var curlink = document.getElementById('Dir'+j);
								curlink.innerHTML = dirn.getDistance().html.replace("mi", "miles").replace("ft", "feet")*/
								//arrayAddress[j][11] = dirn.getDistance().html.replace("mi", "miles").replace("ft", "feet")
								//alert(arrayAddress[j][11]);
								/*if(j != resultCnt)
								{
									if(arrayAddress[j][2])
									{
										var destaddr2 = arrayAddress[j][2] + " " + arrayAddress[j][4] + " " + arrayAddress[j][3] + " " + arrayAddress[j][5] 
									}else{
										var destaddr2 = arrayAddress[j][4] + " " + arrayAddress[j][3] + " " + arrayAddress[j][5] 
									}
									fnLoad(destaddr2, from  , j+1);
								}else{
									AddPaging()
								}
								/*alert(document.getElementByID('Dir'+j).innerHTML);
								document.getElementByID('Dir'+j).innerHTML = dirn.getDistance().html*/
								
						  });
						  
						  dirn.load("from: " + from.replace("Pennsylvania Hospital", "800 Spruce St").replace("Penn Presbyterian Medical Center", "38th and Market Streets").replace("Hospital of the University of Pennsylvania", "3400 Spruce St").replace("Perelman Center for Advanced Medicine", "3400 Civic Center Boulevard") + " to: " + to.replace("Radnor", "Wayne").replace("605 West", "W").replace("One Union Street", "Union St").replace("Pennsylvania Hospital", "800 Spruce St") , "en_US");					
						  //geocoder.getLatLng(destaddr2, function(point){arrayPoint[j] = new GLatLng(point.lat(), point.lng());})	
						   
					  /* }
				   })	*/

               
				

        } 
		var pager = new Pager('LocTable', 10); 
function intervalCheck(len, to)
{
	var doneload = true
	//alert(repeats);
	for (j=len;j>=0;j--)
	{ 
	alert(arrayAddress[j][11][0])
		if(arrayAddress[j][11][0] == undefined)
		{
			/*alert("from: " + arrayAddress[j][2] + " " + arrayAddress[j][4] + " " + arrayAddress[j][3] + " " + arrayAddress[j][5] + " to: " + to)
			arrayAddress[j][11] = dirn.load("from: " + arrayAddress[j][2] + " " + arrayAddress[j][4] + " " + arrayAddress[j][3] + " " + arrayAddress[j][5] + " to: " + to , "en_US");	*/
			doneload = false
		}
	}
	repeats = repeats + 1
	if(doneload == true)
	{
		clearInterval(Interval);
		AddPaging()
	}
	else
	{
		return false;
	}
}
function AddPaging(){
	if(resultCnt == -1)
	{
		do_xml("rerun", lat1, lng1);
	}else{
		
		val = document.Locations.mapaddress.value;
		lat1 = null
		lng1 = null
		pager.init(); 
		pager.showPageNav('pager', 'map-utilities', 1, 'none'); 
		//pager.showPageNav('pager', 'pageNavPosition2', 2); 
		//pager.showPage(1);
	}
}
function mySorting(a,b) {
a = a[11][0];
b = b[11][0];
return a == b ? 0 : (a < b ? -1 : 1)
}

function onGDirectionsLoad(){ 
	//setTimeout("setInitialZoom()", 5000);
	/*document.getElementById("Switch").style.visibility = "visible";
	document.getElementById("Print").style.visibility = "visible";*/
	

	/*if((document.gmaps.origpostalCode.value == "19104" || document.gmaps.origpostalCode.value == "19103" || document.gmaps.origpostalCode.value == "19146") && document.getElementById("SSBridge").style.visibility != "visible"){
	document.getElementById("SSBridge").style.visibility = "visible";
	}else{
	if(document.gmaps.destpostalCode.value != "19104" && document.gmaps.destpostalCode.value != "19103" && document.gmaps.destpostalCode.value != "19146")
	{
	document.getElementById("SSBridge").style.visibility = "hidden";
	}
	}*/
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
 function TextualHybridControl() {
    }
    TextualHybridControl.prototype = new GControl();

    // Creates a one DIV for each of the buttons and places them in a container
    // DIV which is returned as our control element. We add the control to
    // to the map container and return the element for the map class to
    // position properly.
   TextualHybridControl.prototype.initialize = function(map) {
      var container = document.createElement("div");

      var hybridDiv = document.createElement("div");
      this.setButtonStyle_(hybridDiv);
      container.appendChild(hybridDiv);
      hybridDiv.appendChild(document.createTextNode("Traffic"));
      GEvent.addDomListener(hybridDiv, "click", function() {
        
		toggleTrafficView();
      });

      map.getContainer().appendChild(container);
      return container;
    }

    // By default, the control will appear in the top left corner of the
    // map with 7 pixels of padding.
    TextualHybridControl.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(262, 7));

    }

    // Sets the proper CSS for the given button element.
    TextualHybridControl.prototype.setButtonStyle_ = function(button) {
      button.style.textDecoration = "none";
      button.style.color = "#333";
      button.style.backgroundColor = "#ffffff";
	  button.style.backgroundRepeat ="no-repeat";
	  button.style.backgroundPosition ="4px 0px";
	  button.style.borderColor = "#000000";
	  button.style.borderWidth = "1px 1px 1px 1px";
	  button.style.borderStyle = "solid";
      button.style.font = "small Arial";
      button.style.paddingLeft = "20px";
      button.style.paddingRight = "20px";
      button.style.paddingTop = "1px";
      button.style.paddingBottom = "1px";
      button.style.fontSize = "12px";
      button.style.textAlign = "center";
      button.style.cursor = "pointer";
    }
	
	function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	   alert("Google was unable to find that location. Try adding more details such as state or zipcode");
	     /*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: " + gdir.getStatus().code);*/
	   else if (gdir.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: " + gdir.getStatus().code);
	   
	   else if (gdir.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: " + gdir.getStatus().code);

	//   else if (gdir.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: " + gdir.getStatus().code);
	     
	   else if (gdir.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: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}
	
	var newMarkers = [];
	var latLngs = [];
	var icons = [];
	
	function onGDirectionsAddOverlay(){ 
	// Remove the draggable markers from previous function call.
	for (var i=0; i<newMarkers.length; i++) 
	{	
		if(newMarkers[i])
		{
			map.removeOverlay(newMarkers[i]);
		}
	}

	// Loop through the markers and create draggable copies
	for (var i=0; i<=gdir.getNumRoutes(); i++) 
		{
		var originalMarker = gdir.getMarker(i);
		latLngs[i] = originalMarker.getLatLng();
		icons[i] = originalMarker.getIcon();
		newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true});
		//map.addOverlay(newMarkers[i]);

		// Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
		GEvent.addListener(newMarkers[i], "dragend", function()
		  {
		var points = [];
		for (var i=0; i<newMarkers.length; i++) 
			{
		points[i]= newMarkers[i].getLatLng();
			}
		gdir.loadFromWaypoints(points);
		  });

		//Bind 'click' event to original hidden marker
		copyClick(newMarkers[i],originalMarker);
		
		// hide or remove the original marker
		//originalMarker.hide();
		if(originalMarker)
		{
		map.removeOverlay(originalMarker);
		}
		
		}
		
		function copyClick(newMarker,oldMarker){
		GEvent.addListener(newMarker, 'click', function()
		  {GEvent.trigger(oldMarker,'click');
		  });
		}
	}
	
	function loadcameras(latlng, id) {
		//alert(window["done" + id] + " - " + id);
		
		window["object" + id] = new GStreetviewClient();
		//if(window["done" + id] != true){
		//alert(window["done" + id] + " - " + id);
	window["object" + id].getNearestPanorama(latlng, function(reply) {
		//if(document.getElementById('campic'+id).src == "images/camera_dr3.png"){

			  if (reply.code != 200) {
				//icon.setLatLng(lastIconLocation);
				//alert(document.getElementById('campic'+id).src);
			  if(document.getElementById('campic'+id).src == "http://pennhealth.com/images/camera_dr3.png"){
				IsCamera = false;
				document.getElementById('campic'+id).src = "http://pennhealth.com/images/camera_dr2.png"
				window["done" + id] = true;
				}

			  } else {
			  if(document.getElementById('campic'+id).src != "http://pennhealth.com/images/camera_dr1.png"){
				IsCamera = true;
				document.getElementById('campic'+id).src = "http://pennhealth.com/images/camera_dr1.png"
				window["done" + id] = true;
				}
				//alert(document.getElementById('campic'+id).src);
			  }
 
			
				 //}
			  //alert(document.getElementById('campic'+id).src);
          });
		  //}
	
	/*if(IsCamera == false){
	document.getElementbyId("campic" + id).src = "images/camera_dr2.png"
	}else{
	document.getElementbyId("campic" + id).src = "images/camera_dr1.png"
	}
	alert(IsCamera);*/
	
	}

			 // ============ custom direction panel ===============
      function customPanel(map,mapname,gdir,div) {
        var html = "";
		
      
        // ===== local functions =====
		function pause(numberMillis) { 
		var browserName=navigator.appName; 
        var dialogScript = 
           'window.setTimeout(' +
           ' function () { window.close(); }, ' + numberMillis + ');';
         
		if (browserName=="Microsoft Internet Explorer")
 {

// For IE5.
 var result = window.showModalDialog(
           'javascript:document.writeln(' +
            '"<script>' + dialogScript + '<' + '/script>")');
}else{
// For NN6, but it requires a trusted script.
         var result = openDialog(
           'javascript:document.writeln(' +
            '"<script>' + dialogScript + '<' + '/script>"',
           'pauseDialog', 'modal=1,width=10,height=10');

 }
		}
		

        // === waypoint banner ===
        function waypoint(point, type, address) {
          var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
          html += '<table style="border: 1px solid silver; margin: 10px 0px; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0);">';
          html += '  <tr style="cursor: pointer;" onclick='+target+'>';
          html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
          html += '      <img src="http://pennhealth.com/images/camera_dr2.png">'
          //html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon-dd-' +type+ '-trans.png">'
          html += '    </td>';
          html += '    <td style="vertical-align: middle; width: 100%;">';
          html +=        address;
          html += '    </td>';
          html += '  </tr>';
          html += '</table>';
		 /* html += '<table>';
          html += '  <tr style="cursor: pointer;" >';
          html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
          html += '&nbsp;</td>';
          html += '  </tr>';
          html += '</table>';*/

        }

        // === route distance ===
        function routeDistance(dist) {
          html += '<div style="text-align: right; padding-bottom: 0.3em;">' + dist + '</div>';
        }  
		    		
		// === step detail ===
        function detail(point, num, description, dist) {
          var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
		  var camera = 'cameraCheck(new GLatLng(' + point.toUrlValue(6) + '));';
		  var picload = 'loadcameras(new GLatLng(' + point.toUrlValue(6) + '), ' + num + ')';
		  
          html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
          html += '  <tr style="cursor: pointer;" >';
          html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;" onclick='+target+'>';
          html += '      <a href="javascript:void(0)"> '+num+'. </a>';
          html += '    </td>';
          html += '    <td style="width:450px; border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; " onclick='+target+'>';
          html +=        description;
          html += '    </td>';
          html += '    <td style="width:5px;border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;" onclick='+target+'>';
          html +=        dist;
          html += '    </td>';
          html += '    <td style="width:20px; border-top: 1px solid rgb(205, 205, 205); margin: 0px; vertical-align: top; text-align: right;" >';
		  html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
		  html += '  <tr style="cursor: pointer;"  onclick="' + camera +'">';
		  html += '    <td align="right" style="vertical-align: top; text-align: right;">';
		  html += '<img id="campic' + num + '" src="http://pennhealth.com/images/camera_dr3.png" onload="setTimeout(&#39;' + picload + '&#39;, 100*' + num + ');"/>';
		  html += '		</td>';
		  html += '  </tr>';
		  html += '</table>';
          html += '    </td>';
          html += '  </tr>';
          html += '</table>';
		  

        }

        // === Copyright tag ===
        function copyright(text) {
          html += '<div style="font-size: 0.86em;">' + text + "</div>";
        }
        

        // === read through the GRoutes and GSteps ===

        for (var i=0; i<gdir.getNumRoutes(); i++) {
          if (i==0) {
            var type="play";
          } else {
            var type="pause";
          }
          var route = gdir.getRoute(i);
          var geocode = route.getStartGeocode();
          var point = route.getStep(0).getLatLng();
          // === Waypoint at the start of each GRoute
		  var origin = geocode.address;
          waypoint(point, type, geocode.address);
          routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");
		 
		
          for (var j=0; j<route.getNumSteps(); j++) {
            var step = route.getStep(j);
            // === detail lines for each step ===
			
			//client.getNearestPanorama(step.getLatLng(), cameraCheck);
			//window.focus();
			//pause(200);
			//alert(step.getLatLng());			
	            detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
          }
		  
        }

        // === the final destination waypoint ===   
        var geocode = route.getEndGeocode();
        var point = route.getEndLatLng();
		var destination = geocode.address;
        waypoint(point, "stop", geocode.address);
                 
        // === the copyright text ===
        copyright(gdir.getCopyrightsHtml());
		
        // === drop the whole thing into the target div
		window.location.hash="themap";
        div.innerHTML = html + "</br><a style=\"color:#0033FF;font-weight:bolder;cursor:pointer\" name=\"Switch\" id=\"Switch\" onclick=\"\">Reverse</a>&nbsp;&nbsp;<a style=\"color:#0033FF;font-weight:bolder;cursor:pointer\" name=\"Print\" id=\"Print\" onclick=\"\">Print</a>"
		
		document.getElementById("Switch").onclick = function() {
			  reverseDirections(destination, origin, "en_US");
			}

      } // ============ end of customPanel function ===========


	function setStreetOptions(lat, lng) {
	  var latlng = new GLatLng(lat, lng);
	  //map.setCenter(latlng, 13);
	
	  var guyIcon = new GIcon(G_DEFAULT_ICON);
	  guyIcon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png";
	  guyIcon.transparent = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png";
	  guyIcon.imageMap = [
			26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26,
			16,20, 16,14, 19,13, 22,8
		 ];
	  guyIcon.iconSize = new GSize(49, 52);
	  guyIcon.iconAnchor = new GPoint(25, 35);  // near base of guy's feet
	  guyIcon.infoWindowAnchor = new GPoint(25, 5);  // top of guy's head
	
	  icon = new GMarker(latlng, {icon: guyIcon, draggable: true});
	  lastIconLocation = latlng;
	  GEvent.addListener(icon, "dragend", onDragEnd);
	  GEvent.addListener(icon, "click", openPanoramaBubble);
	  //toggleStreetView();
	}
	function showDefault(address) {
	var html = "<table cellpadding='0' cellspacing='0' border='0' width='300'><tr><td valign='top' align='center'><img src='http://pennhealth.com/images/uphs_shield.gif' /></td><td valign='top'><div style='line-height:120%;font-weight: bold;color:#1a3c79;'>" + document.gmaps.destpracname.value + "</div>" + document.gmaps.destaddress.value + "<br>" + document.gmaps.destcity.value + ", " + document.gmaps.deststateProvince.value + "  " + document.gmaps.destpostalCode.value + "</td></tr></table>"
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " nnot found");
            } else {
			  defaultLat = point.lat();
			  defaultLng = point.lng();
              //map.setCenter(point, 13);
              marker = new GMarker(point);
              map.addOverlay(marker);
              marker.openInfoWindowHtml(html);
			  GEvent.addListener(marker, "click", function() { 
              marker.openInfoWindowHtml(html); }); 

            }
          }
        );
      }
    }
	
	function toggleTrafficView() {
      if (toggleTraffic == 1) {
		  if(gto){
        map.removeOverlay(gto);
		  }
        toggleTraffic = 0;
      } else {
        map.addOverlay(gto);
        toggleTraffic = 1;
      }
    }
    
	function toggleStreetView() {
	  if (!overlayInstance) {
		overlayInstance = new GStreetviewOverlay();
		map.addOverlay(overlayInstance);
		if(markergone == true)
		{
		setStreetOptions(map.getCenter().lat(), map.getCenter().lng());
		}else{
		setStreetOptions(defaultLat, defaultLng);
		}
		map.addOverlay(icon);
		map.setZoom(currentZoom);
	  } else {
		  if (overlayInstance){
		map.removeOverlay(overlayInstance);
		  }
		   if (icon){
		map.removeOverlay(icon);
		   }
		overlayInstance = null;
	  }
      /*if (toggleStreet == 1) {
        map.removeOverlay(svOverlay);
        toggleStreet = 0;
      } else {
        map.addOverlay(svOverlay);
        toggleStreet = 1;
      }*/
    }
	
    function setDirections(destination, origin, locale) {

	  gdir.load("from: " + origin + " to: "  + destination,{getSteps:true});
		
	  
		
		if(markergone == false){
			if(marker){
		map.removeOverlay(marker);
		markergone = true;
			}
		}
    }
	
    function reverseDirections(destination, origin, locale) {
	 // gdir.clear();  
	  gdir.load("from: " + destination + " to: "  + origin,{getSteps:true});
	  document.getElementById("Switch").onclick = function() {
			  setDirections(destination, origin, locale);
			}

    }
	
	function openPanoramaBubble(point) {

	  var contentNode = document.createElement('div');
	  contentNode.style.textAlign = 'center';
	  contentNode.style.width = '500px';
	  contentNode.style.height = '300px';
	  contentNode.innerHTML = 'Loading panorama';
	  map.openInfoWindow(point, "<div id='pano' style='width:200px;height:200px;'></div>", {maxContent: contentNode, maxTitle: "Full screen"});
	
	  panorama = new GStreetviewPanorama(document.getElementById("pano"));
	  panorama.setLocationAndPOV(point, null);
	  GEvent.addListener(panorama, "newpano", onNewLocation);
	  GEvent.addListener(panorama, "yawchanged", onYawChange); 
	  GEvent.addListener(panorama, "error", handleNoFlash);
	
	  var iw = map.getInfoWindow();
	  window.setTimeout("map.getInfoWindow();", 5);
	  GEvent.addListener(iw, "maximizeend", function() {
		panorama.setContainer(contentNode);  
		window.setTimeout("panorama.checkResize()", 5);
	  });
	}
	
	function handleNoFlash(errorCode) {
      if (errorCode == FLASH_UNAVAILABLE) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
      }
    }  
		
	function onYawChange(newYaw) {
	  var GUY_NUM_ICONS = 16;
	  var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
	  if (newYaw < 0) {
		newYaw += 360;
	  }
	  guyImageNum = Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
	  guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + guyImageNum + ".png";
	  icon.setImage(guyImageUrl);
	}
	
	function onNewLocation(lat, lng) {
	  var latlng = new GLatLng(lat, lng);
	  icon.setLatLng(latlng);
	}
	
	function onDragEnd() {
	  var latlng = icon.getLatLng();
	  if (panorama) {
		client.getNearestPanorama(latlng, onResponse);
	  }
	}
	
	function cameraCheck(response) {
	//alert(response);
	if(panorama && isOldIE){
	panorama.remove();
	contentNode = "";
	}
	client.getNearestPanorama(response, function(reply) {
	  if (reply.code != 200) {
		//icon.setLatLng(lastIconLocation);
		alert("Not image");
	  } else {
	  //if(document.getElementById('campic'+id).src == "http://pennhealth.com/images/camera_dr1.png"){
 	  var contentNode = document.createElement('div');
	  contentNode.style.textAlign = 'center';
	  contentNode.style.width = '450px';
	  contentNode.style.height = '300px';
	  contentNode.innerHTML = 'Loading panorama';
	  if(isOldIE){
	  map.openInfoWindowHtml(response, "<div id='pano' style='width:250px;height:250px;'></div>");
	  }else{
	  map.openInfoWindowHtml(response, "<br/><div id='pano' style='width:225px;height:225px;'></div>", {maxContent: contentNode, maxTitle: "FullScreen", onOpenFn: function() { 
			panorama = new GStreetviewPanorama(document.getElementById("pano"));
	  //alert(response);
	  panorama.setLocationAndPOV(response);
	  GEvent.addListener(panorama, "newpano", onNewLocation);
	  GEvent.addListener(panorama, "yawchanged", onYawChange); 
	  GEvent.addListener(panorama, "error", handleNoFlash);
	  //GEvent.addListener(panorama, "flashstart", flashStarted);																																								
																																															} }
      ); 
	  }
	
	  

	  
	
	  var iw = map.getInfoWindow();
	  
	  GEvent.addListener(iw, "maximizeend", function() {
		panorama.setContainer(contentNode);  
		window.setTimeout("panorama.checkResize()", 5);
	  });	 // }
	  }
          });
	 /* if (response.code != 200) {
		//icon.setLatLng(lastIconLocation);
		IsCamera = false;
	  } else {
	  	IsCamera = true;
	  }*/
	  //alert(IsCamera);
	  
	}
		
		function flashStarted(reqq) {
     
        //alert("Yay! it started");
        return;

    }  
	
	
	function cameraResponse(response) {
	  if (response.code != 200) {
		//icon.setLatLng(lastIconLocation);
		alert("Not image");
	  } else {
	  //if(document.getElementById('campic'+id).src == "http://pennhealth.com/images/camera_dr1.png"){
 	  var contentNode = document.createElement('div');
	  contentNode.style.textAlign = 'center';
	  contentNode.style.width = '500px';
	  contentNode.style.height = '300px';
	  contentNode.innerHTML = 'Loading panorama';
	  map.openInfoWindow(response, "<div id='pano' style='width:200px;height:200px;'></div>", {maxContent: contentNode, maxTitle: "Full 			screen"});
	
	  panorama = new GStreetviewPanorama(document.getElementById("pano"));
	  //alert(response);
	  panorama.setLocationAndPOV(response);
	  GEvent.addListener(panorama, "newpano", onNewLocation);
	  GEvent.addListener(panorama, "yawchanged", onYawChange); 
	  GEvent.addListener(panorama, "error", handleNoFlash);
	
	  var iw = map.getInfoWindow();
	  GEvent.addListener(iw, "maximizeend", function() {
		panorama.setContainer(contentNode);  
		window.setTimeout("panorama.checkResize()", 5);
	  });	 // }
	  }
	}	

	
	function onResponse(response) {
	  if (response.code != 200) {
		icon.setLatLng(lastIconLocation);
	  } else {
		var latlng = new GLatLng(response.Location.lat, response.Location.lng);
		icon.setLatLng(latlng);
		lastIconLocation = latlng;
		openPanoramaBubble();
	  }
	}	
	
	
	function setInitialZoom()
	{
		currentZoom = map.getZoom();
	}
	
	function findAndReplace(searchText, replacement, searchNode) {
    if (!searchText || typeof replacement === 'undefined') {
        // Throw error here if you want...
        return;
    }
    var regex = typeof searchText === 'string' ?
                new RegExp(searchText, 'g') : searchText,
        childNodes = (searchNode || document.body).childNodes,
        cnLength = childNodes.length,


        excludes = 'html,head,style,title,link,meta,script,object,iframe';
    while (cnLength--) {
        var currentNode = childNodes[cnLength];
        if (currentNode.nodeType === 1 &&
            (excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
            arguments.callee(searchText, replacement, currentNode);
        }
        if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
            continue;
        }
        var parent = currentNode.parentNode,
            frag = (function(){
                var html = currentNode.data.replace(regex, replacement),
                    wrap = document.createElement('div'),
                    frag = document.createDocumentFragment();
                wrap.innerHTML = html;
                while (wrap.firstChild) {
                    frag.appendChild(wrap.firstChild);
                }
                return frag;
            })();
        parent.insertBefore(frag, currentNode);
        parent.removeChild(currentNode);
    }
}
var gAutoPrint = true; // Flag for whether or not to automatically call the print function

function printSpecial()
{
	if (document.getElementById != null)
	{
		var html = '<HTML>\n<HEAD>\n';

		if (document.getElementsByTagName != null)
		{
			var headTags = document.getElementsByTagName("head");
			if (headTags.length > 0)
				html += headTags[0].innerHTML;
		}
		
		html += '\n</HE' + 'AD>\n<BODY>\n';
		
		var printReadyElem = document.getElementById("printReady");
		
		if (printReadyElem != null)
		{
				html += printReadyElem.innerHTML;
		}
		else
		{
			alert("Could not find the printReady section in the HTML");
			return;
		}
			
		html += '\n</BO' + 'DY>\n</HT' + 'ML>';
		
		var printWin = window.open("","printSpecial");
		printWin.document.open();
		printWin.document.write(html);
		printWin.document.close();
		if (gAutoPrint)
			printWin.print();
	}
	else
	{
		alert("Sorry, the print ready feature is only available in modern browsers.");
	}
}

function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert("The parent div cannot be removed.");
     }
     else if (document.getElementById(childDiv)) {     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
     }
     else {
          //alert("Child div has already been removed or does not exist.");
          return false;
     }
}

function WordCnt(val)
{
var fullStr = val + " ";
var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
var splitString = cleanedStr.split(" ");
var word_count = splitString.length -1;	
return word_count;
}
function getArgs() { 
		var args = new Object(); 
		var query = location.search.substring(1); 
		var pairs = query.split("&"); 
		for(var i = 0; i < pairs.length; i++) 
		{ 
			var pos = pairs[i].indexOf('='); 
			if (pos == -1) continue; 
			var argname = pairs[i].substring(0,pos); 
			var value = pairs[i].substring(pos+1); 
			value = value.replaceAll("+", " ")
			args[argname] = unescape(value); 
		} 
			return args; 
} 
		
